2024-06-16 11:39:13 发布
网友
我有以下字符集:
qwertyiopnmjk013
我想生成所有可能的字符串,包括6个字符和7个字符,注意每个字母在同一个生成的字符串中只出现一次。在
在python中,哪种形式是最好的呢?有什么例子吗?在
现在我把字符集复制到另一个变量中,然后我开始生成挑选的字母,并从字符集中删除它们,然后继续前进,但我认为这不是最好的方法。。在
使用itertools:
import itertools myStr = "qwertyiopnmjk013" chars = list(myStr) for comb in itertools.combinations(chars, 6): print comb
这个问题有点模棱两可,但以下是所有部分。 首先,为了得到组合:
import itertools source = "qwertyiopnmjk013" map(''.join, itertools.combinations(source, 6))
现在,如果你不想重复字母即使你的源字符串 包含重复项,然后首先使用以下内容修复源字符串:
如果你还想让每一个组合按顺序排列, 那么你要处理的是排列,而不是组合。要想把两者都列入一个好名单:
reduce(lambda x, y: x + y, map(lambda x: map(''.join, itertools.permutations(x)), itertools.combinations(source, 6)))
你应该注意到,在这一点上,你正在进入一千万个字符串;希望你有一个快速的机器。在
您可以使用itertools.combinations:
itertools.combinations
import itertools s = "qwertyiopnmjk013" final_letters = [''.join(b) for b in [i for i in itertools.combinations(s, 6)]+[i for i in itertools.combinations(s, 7)] if len(set(b)) == len(b)]
使用itertools:
这个问题有点模棱两可,但以下是所有部分。 首先,为了得到组合:
现在,如果你不想重复字母即使你的源字符串 包含重复项,然后首先使用以下内容修复源字符串:
^{pr2}$如果你还想让每一个组合按顺序排列, 那么你要处理的是排列,而不是组合。要想把两者都列入一个好名单:
你应该注意到,在这一点上,你正在进入一千万个字符串;希望你有一个快速的机器。在
您可以使用
itertools.combinations
:相关问题 更多 >
编程相关推荐