【问题标题】:Generate all possible combinations of elements in a list生成列表中所有可能的元素组合
【发布时间】:2017-08-30 15:30:47
【问题描述】:

我一直在尝试创建一个脚本,其中将打印列表的每个可能组合[其中 (1,2) 和 (2,1) 将被视为不同的条目]。 例如:

c = [1,2]
# do something magical
print(c with magical stuff) 
>>>[(1), (2), (1, 1), (1, 2), (2, 1), (2, 2)]

我已经尝试过 itertools.permutations。它显示输出为 >>> () (1,) (​​2,) (1, 2) (2, 1)。但是,它不包括 (1, 1) 和 (2,2)

我们将不胜感激任何帮助。我是编码新手(我非常擅长打印“Hello World!”:3)

【问题讨论】:

标签: python list tuples combinations itertools


【解决方案1】:

试试itertools.product:

def foo(l):
    yield from itertools.product(l)
    yield from itertools.product(l, l)

for x in foo([1, 2]):
     print(x)

(1,)
(2,)
(1, 1)
(1, 2)
(2, 1)
(2, 2)

请注意,yield from 语法从 python3.3 开始可用。

【讨论】:

    【解决方案2】:

    为我工作:

    c = [1,2]
    for i in itertools.permutations(c):
         print i
    

    产量

    (1, 2)
    (2, 1)
    

    【讨论】:

    • 谢谢。确实如此。但是,它并没有结合所有元素,如 (1, 1) 和 (2, 2)。抱歉标题令人困惑。
    【解决方案3】:

    可能有一些内置的(或者更可能是 numpy)包可以为你做这件事,但你自己做是一个很好的练习。

    一个问题 - 您是只对长度为 2 的排列感兴趣,还是想为任意长度的排列编写一个函数?

    另请参阅:How to generate all permutations of a list in Python

    【讨论】:

    • 这并不能真正回答问题。
    • @cᴏʟᴅsᴘᴇᴇᴅ 然而,这表明他值得评论所需的 50 次代表。无论如何,这就是我投票的原因。但 Coldspeed 是对的,迈克。这将更适合作为评论,而不是答案。
    • 不确定是否适合编写初学者的示例,选择提供一些高级想法
    【解决方案4】:

    使用替换进行组合,然后排列结果,只保留唯一的结果。

    import itertools as it 
    
    
    combs = it.chain.from_iterable(it.combinations_with_replacement(c, i) for i in range(1,3))
    perms = it.chain.from_iterable([set(it.permutations(i)) for i in combs])
    list(perms)
    # [(1,), (2,), (1, 1), (1, 2), (2, 1), (2, 2)]
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 2017-08-13
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多