1

我有一个清单[".","_","<<",">>"]

我需要的是获取长度为 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 或更多的长度怎么办?

4

2 回答 2

3

用于itertools.product()为您生成组合,无需嵌套循环:

from itertools import product

mylist = [".", "_", "<<", ">>"]
length = 4
for chars in product(mylist, repeat=length):
    print ''.join(chars)

只需调整length变量以获得更长的组合。

于 2013-09-11T11:43:37.427 回答
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)])
于 2013-09-11T11:43:52.790 回答