繁体   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