【问题标题】:Subtract all items in a list against each other将列表中的所有项目相互减去
【发布时间】:2016-01-11 10:56:11
【问题描述】:

我在 Python 中有一个如下所示的列表:

myList = [(1,1),(2,2),(3,3),(4,5)]

我想将每个项目与其他项目相减,如下所示:

(1,1) - (2,2)
(1,1) - (3,3)
(1,1) - (4,5)
(2,2) - (3,3)
(2,2) - (4,5)
(3,3) - (4,5)

预期的结果将是一个包含答案的列表:

[(1,1), (2,2), (3,4), (1,1), (2,3), (1,2)]

我该怎么做?如果我使用for 循环来处理它,我也许可以存储前一个项目并与我当时正在使用的项目进行检查,但它并没有真正起作用。

【问题讨论】:

  • 什么是(1 , 1) - (2 , 2)(-1, -1) 还是别的什么?
  • @BoristheSpider,是的,(-1,-1) 或 (1,1)。要么,我不在乎这个标志。

标签: python list tuples combinations


【解决方案1】:

使用itertools.combinations 和元组解包来生成差异对:

>>> from itertools import combinations
>>> [(y1-x1, y2-x2) for (x1, x2), (y1, y2) in combinations(myList, 2)]                    
[(1, 1), (2, 2), (3, 4), (1, 1), (2, 3), (1, 2)]

【讨论】:

    【解决方案2】:

    您可以使用列表推导式,使用np.subtract 将元组相互“减去”:

    import numpy as np
    
    myList = [(1,1),(2,2),(3,3),(4,5)]
    
    answer = [tuple(np.subtract(y, x)) for x in myList for y in myList[myList.index(x)+1:]]
    print(answer)
    

    输出

    [(1, 1), (2, 2), (3, 4), (1, 1), (2, 3), (1, 2)]
    

    【讨论】:

      【解决方案3】:

      operator.subcombinations 一起使用。

      >>> from itertools import combinations
      >>> import operator
      >>> myList = [(1, 1),(2, 2),(3, 3),(4, 5)]
      >>> [(operator.sub(*x), operator.sub(*y)) for x, y in (zip(ys, xs) for xs, ys in combinations(myList, 2))]
      [(1, 1), (2, 2), (3, 4), (1, 1), (2, 3), (1, 2)]
      >>>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-27
        • 2019-06-28
        • 1970-01-01
        • 1970-01-01
        • 2020-04-21
        • 2017-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多