【发布时间】:2019-10-15 11:08:04
【问题描述】:
我需要在列表中创建所有项组合。我尝试过使用itertools 的所有部分,例如permutations、combinations、combinations_with_replacement,但它们似乎都几乎“计数”了。例如,使用以下代码:
from itertools import combinations_with_replacement
hex_chars = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
perm = combinations_with_replacement(hex_chars, 5)
for i in list(perm):
print(i)
它产生:
('0', '0', '0', '0', '0')
('0', '0', '0', '0', '1')
('0', '0', '0', '0', '2')
('0', '0', '0', '0', '3')
('0', '0', '0', '0', '4')
('0', '0', '0', '0', '5')
('0', '0', '0', '0', '6')
('0', '0', '0', '0', '7')
('0', '0', '0', '0', '8')
('0', '0', '0', '0', '9')
('0', '0', '0', '0', 'a')
('0', '0', '0', '0', 'b')
('0', '0', '0', '0', 'c')
('0', '0', '0', '0', 'd')
('0', '0', '0', '0', 'e')
('0', '0', '0', '0', 'f')
('0', '0', '0', '1', '1')
我需要它来生成几乎所有可能的组合,例如,您会注意到它不会生成“000010”,如果放置时间足够长,它也不会生成诸如“A000A”之类的字符串。我需要生成字符串长度为 5 的所有组合(包括重复项),然后我需要将它们全部保存到外部文本文件中。而且,为了澄清,我的意思是每一个可能的组合,例如“A0000”、“0A000”、“00A00”、“000A00”、“0000A0”、“00000A”。
【问题讨论】:
-
这不是组合 -
00010与00001相同,就组合而言(a000a和000aa类似)。 -
lst = list(itertools.product(hex_chars, repeat=5))
-
@jonrsharpe,我需要每个可能的字符串组合,在每个可能的序列中,所以我需要 a000a、0a00a、00a0a、000aa、10000、01000、00100、00010、00001,我之前查看过重复项发布这个,它并没有解决我的问题
-
重复的答案确实提供了这一点,因此请更详细地说明您仍需要了解的内容。
标签: python list combinations permutation itertools