我有一个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
以便相互"减去"元组:
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)]