簡體   English   中英

獲取列表中所有可能的字符組合

[英]Get all possible combinations of characters in list

我有一個列表[".","_","<<",">>"]

我需要的是使用所有可能的組合獲得長度為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或更長的長度怎么辦?

使用itertools.product()為您生成組合,沒有嵌套循環:

from itertools import product

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

只需調整length變量即可獲得更長的組合。

您可以為此目的使用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)])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM