简体   繁体   English

在九个位置的列表中查找三个字母的所有组合

[英]Find all combinations of three letters in a list of nine positions

i have a list like:我有一个类似的列表:

['A','B','C']

what i want to obtain is all the combinations of these three letters in a nine length list, it can be with repeated letters.我想要获得的是这三个字母在九长列表中的所有组合,它可以是重复的字母。

for example:例如:

combination_1 = ['A','A','A','A','A','A','A','A','A']
combination_2 = ['A','A','A','A','C','A','A','A','A']
combination_3 = ['B','B','B','A','C','A','A','C','C']

I would like to do it in python but if there is a solution in other language it will work too.我想用 python 来做,但如果有其他语言的解决方案,它也可以。

Combinations with replacement can give it:与替换组合可以给它:

from itertools import combinations_with_replacement

list_ = ["A", "B", "C"]
for comb in combinations_with_replacement(list_, 9):
    print(comb)

Prints印刷

('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A')
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B')
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'C')
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B')
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'C')
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'C', 'C')
('A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B')
('A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'C')
('A', 'A', 'A', 'A', 'A', 'A', 'B', 'C', 'C')
('A', 'A', 'A', 'A', 'A', 'A', 'C', 'C', 'C')
('A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B')
('A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C')
('A', 'A', 'A', 'A', 'A', 'B', 'B', 'C', 'C')
('A', 'A', 'A', 'A', 'A', 'B', 'C', 'C', 'C')
('A', 'A', 'A', 'A', 'A', 'C', 'C', 'C', 'C')
('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B')
('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C')
('A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C')
('A', 'A', 'A', 'A', 'B', 'B', 'C', 'C', 'C')
('A', 'A', 'A', 'A', 'B', 'C', 'C', 'C', 'C')
('A', 'A', 'A', 'A', 'C', 'C', 'C', 'C', 'C')
('A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B')
('A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'C')
....

and more:) (55 in total).等等:)(总共 55 个)。

If you want list outputs, you can print(list(comb)) in the loop above.如果你想要列表输出,你可以在上面的循环中print(list(comb))

(after the comment's correction) (评论更正后)

itertools.product with repeat argument can give it:带有repeat参数的itertools.product可以给它:

from itertools import product

list_ = ["A", "B", "C"]
for comb in product(list_, repeat=9):
    print(comb)

3**9 = 19683 items it produces. 3**9 = 19683个项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM