简体   繁体   English

使用itertools卡在python组合中

[英]Stuck in python combinations using itertools

I'm using the itertools module in python. 我在python中使用itertools模块。 I found that combinations_with_replacement does not give me all the combinations. 我发现Combines_with_replacement不能给我所有组合。

>>>import itertools
>>>[list(x) for x in itertools.combinations_with_replacement('AB', 3)]
[['A', 'A', 'A'], ['A', 'A', 'B'], ['A', 'B', 'B'], ['B', 'B', 'B']]

It does not give me ['A','B','A'] nor ['B','A','B']. 它既不给我['A','B','A'],也不给我['B','A','B']。

Does anyone know why is this and, more importantly, how to correct it? 有谁知道这是为什么,更重要的是,如何纠正它?

Try product with 3 repeats: 尝试3次重复的product

import itertools
print [list(x) for x in itertools.product('AB', repeat=3)]

Gives: 给出:

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

Remember that using list comprehension you can always resort to: 请记住,使用列表推导您始终可以诉诸:

ab_str = "AB"
# don't have to use +, can do (x, y, z,)
print [x + y + z for x in ab_str for y in ab_str for z in ab_str]

Gives: 给出:

['AAA', 'AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA', 'BBB'] ['AAA','AAB','ABA','ABB','BAA','BAB','BBA','BBB']

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

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