簡體   English   中英

集合的所有可能組合作為字符串列表

[英]All possible combinations of a set as a list of strings

我試圖用Python編寫一個函數

def all_strings(alpha,length):
    # ...

它取一個給定的字母( alpha )和一個length並返回受給定長度限制的所有可能的字母組合。

例如:

all_strings({0,1}, 3)

應該返回:

['000', '001', '010', '011', '100', '101', '110', '111']

我嘗試循環遍歷集合,但你不能在python中迭代一個集合。 我也考慮過itertools,但是permutationscombinations不允許重復數字。

您可以使用itertools.product

>>> from itertools import product

>>> list(product({0,1}, repeat=3))
[(0, 0, 0),
 (0, 0, 1),
 (0, 1, 0),
 (0, 1, 1),
 (1, 0, 0),
 (1, 0, 1),
 (1, 1, 0),
 (1, 1, 1)]

您還可以str.join結果來獲取字符串:

>>> list(''.join(map(str, comb)) for comb in product({0,1}, repeat=3))
['000', '001', '010', '011', '100', '101', '110', '111']

如果你關心效率,你也可以將初始集轉換為一組字符串,以最大限度地減少字符串轉換(感謝@Stefan Pochmann在評論中指出這一點):

>>> list(map(''.join, product(map(str, {0,1}), repeat=3)))
['000', '001', '010', '011', '100', '101', '110', '111']

暫無
暫無

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

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