【问题标题】:Python, combinations, permutations without repeatPython,组合,无重复排列
【发布时间】:2014-11-27 11:19:58
【问题描述】:

Python。我有两个列表,长度相同。这个想法是建立配对数据(用于回归分析)。我想出了循环,它看起来像这样。

a=(1,3,5,7)   #first list
b=(2,4,6,10)  #second list
w=zip(a,b)    #paired values from both lists

i=0
j=0
for each in w:
    x= w[i]
    for that in xrange(i,len(w)-1):
        i+=1
        print x, w[i]
    j+=1
    i=j

输出与我预期的一样 - 第一对与第二、第三……依此类推,然后第二对与第三、第四……依此类推(跳过第二对和第一对之间的组合,因为它是有点像第一对和第二对的组合......)

(1, 2) (3, 4)
(1, 2) (5, 6)
(1, 2) (7, 10)
(3, 4) (5, 6)
(3, 4) (7, 10)
(5, 6) (7, 10) [..] and so on as I was expecting.

问题是 - 是否有其他一些更短、优化的方法来重写此代码,也许使用 itertools?

【问题讨论】:

    标签: python optimization combinations combinatorics itertools


    【解决方案1】:

    您可以将itertools.combinationsitertools.izip 一起使用:

    >>> from itertools import izip, combinations
    >>> for a, b in combinations(izip(a, b), 2):
            print a, b
    ...     
    (1, 2) (3, 4)
    (1, 2) (5, 6)
    (1, 2) (7, 10)
    (3, 4) (5, 6)
    (3, 4) (7, 10)
    (5, 6) (7, 10)
    

    【讨论】:

    • 谢谢。您给定的答案代码完全符合我的代码的结果;尽管先生/女士 babbageclunk 给出了更一般的答案;)
    【解决方案2】:

    是的:itertools.combinations

    print list(itertools.combinations(w, 2))
    

    您在问题中提到了这一点 - 我不确定您为什么在 StackOverflow 上提问之前不查看文档。

    【讨论】:

    • :) 我也有这样的时刻。
    猜你喜欢
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多