我有一个列表[".","_","<<",">>"]
我需要的是获得长度为4的所有字符串以及所有可能的组合,其中每个字符都是上面列表中的一个。
示例:
"._<<>>","__<<>>",".<<<<>>" ... etc
现在我这样做的时间长度为4:
mylist = [".","_","<<",">>"]
for c1 in mylist:
for c2 in mylist:
for c3 in mylist:
for c4 in mylist:
print "".join([c1,c2,c3,c4])
但这看起来很难看,如果我需要将它扩展到10或更长的长度呢?
答案 0 :(得分:3)
使用itertools.product()
为您生成组合,无需嵌套循环:
from itertools import product
mylist = [".", "_", "<<", ">>"]
length = 4
for chars in product(mylist, repeat=length):
print ''.join(chars)
只需调整length
变量即可获得更长的组合。
答案 1 :(得分:3)
您可以将itertools.product用于此目的
n = 4
for symbols in itertools.product([".","_","<<",">>"], repeat=n):
print "".join(symbols)
单行:
print "\n".join(["".join(s) for s in itertools.product([".","_","<<",">>"], repeat=n)])