【问题标题】:Every combination of list elements without replacement列表元素的每个组合,无需替换
【发布时间】:2015-09-08 10:58:18
【问题描述】:

在 Python 2.7 中,我想获取列表元素的 self-cartesian product,但没有与自身配对的元素。

 In[]: foo = ['a', 'b', 'c']
 In[]: [x for x in itertools.something(foo)]
Out[]: 
       [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

目前我这样做:

[x for x in itertools.product(foo, repeat=2) if x[0] != x[1]]

但我怀疑有一个内置的方法。这是什么?

注意:itertools.combinations wouldn't give me ('a', 'b')('b', 'a')

【问题讨论】:

    标签: python combinations itertools combinatorics


    【解决方案1】:

    您正在寻找permutations 而不是组合。

    from itertools import permutations
    
    foo = ['a', 'b', 'c']
    print(list(permutations(foo, 2)))
    
    # Out: [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
    

    【讨论】:

    • 文档通过显示 permutations() 可以在删除重复的 product() 方面实现这一点来巧妙地证实了这一点,这正是 OP 正在做的事情。
    猜你喜欢
    • 2020-01-10
    • 2017-02-01
    • 1970-01-01
    • 2015-02-12
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    相关资源
    最近更新 更多