Python,组合,排列无重复

标签 python optimization combinations combinatorics python-itertools

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?

最佳答案

您可以使用 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)

关于Python,组合,排列无重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27169444/

相关文章:

python - 在 python 脚本中运行 bash 命令 X 秒

python - dtype 比较 : == and isin produce different results for "object"

python - WXPython Video MediaCtrl 自定义按钮

c++ - Cython - 实现回调

sql - 当按来自两个不同表的列排序时,PostgreSQL 查询速度变慢

java - 在Java深度生成列表n层的所有组合

C++,数组元素不按顺序组合

python - 计算 pandas 数据框中唯一组合的数量

r - 加速大型数据帧中的 3 列 R 搜索

python - 优化二维数组