繁体   English   中英

相互减去列表中的所有项目

[英]Subtract all items in a list against each other

我有一个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循环接近它,我可以存储前一个项目并检查当时我正在使用的项目,但它确实不起作用。

使用带有元组解包的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)]

您可以使用列表np.subtract ,使用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)]

使用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)]
>>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM