我有一个包含一些元素的列表,我想创建一个列表,我将这些项目组合在一起3到3.直到现在我设法做到这一点,但我无法想象如何组合重复元素。到目前为止,我的代码就是这个:
list_of_aa = ["A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F", "P", "S", "T", "W", "Y", "V"]
combinations = list(itertools.combinations(list_of_aa, 3))
但是使用这段代码,我错过了像“AAA”或“MAA”这样的三胞胎。你知道我怎么能解决这个问题?谢谢。
答案 0 :(得分:2)
您希望拥有商品的笛卡尔产品,因此请使用itertools.product()
:
itertools.product(list_of_aa, repeat=3)
请注意,这会产生len(list_of_aa) ** 3
(因此多维数据集)元素数量,您可能希望避免将所有元素都实现到列表中。对于您的样本输入,将生成8000个3元素元组。
从整个结果中取出切片:
>>> from itertools import product, islice
>>> list_of_aa = ["A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F", "P", "S", "T", "W", "Y", "V"]
>>> for combo in islice(product(list_of_aa, repeat=3), 5):
... print(''.join(combo))
...
AAA
AAR
AAN
AAD
AAC
>>> for combo in islice(product(list_of_aa, repeat=3), 1000, 1005):
... print(''.join(combo))
...
NLA
NLR
NLN
NLD
NLC
>>> for combo in islice(product(list_of_aa, repeat=3), 2000, 2005):
... print(''.join(combo))
...
QAA
QAR
QAN
QAD
QAC