我有两个Long
值的元组。我需要它们的差异,比如x2-x1
.
x1 =
(2873120768, 2873122560, 2873123328)
x2 =
(2873121279, 2873122815, 2873123583)
预期成果:
result = (511,255,255)
但不管是元组还是列表
如果可能的话,我正在寻找一种不逐个元素进行操作的方法。速度是一个限制。我搜索了它,但找不到答案。
提前谢谢你
您可以zip
元组,迭代对并在列表推导中执行减法。
>>> x1 = (2873120768, 2873122560, 2873123328)
>>> x2 = (2873121279, 2873122815, 2873123583)
>>> [j - i for i,j in zip(x1,x2)]
[511, 255, 255]
在纯 Python 中,最快的方法是将 map
与 operator.sub
一起使用:
>>> from operator import sub
>>> map(sub, x2, x1)
[511L, 255L, 255L]
#If you want tuple as output
>>> from itertools import imap
>>> tuple(imap(sub, x2, x1))
(511L, 255L, 255L)
如果这还不够,请切换到 Numpy:
>>> x1_arr = np.array(x1)
>>> x2_arr = np.array(x2)
>>> x2_arr - x1_arr
array([511, 255, 255])
让我们计时:
>>> x1 = (2873120768L, 2873122560L, 2873123328L)*10**5
>>> x2 = (2873121279L, 2873122815L, 2873123583L)*10**5
>>> %timeit map(sub, x2, x1)
100 loops, best of 3: 19.3 ms per loop
>>> %timeit tuple(imap(sub, x2, x1))
10 loops, best of 3: 19.9 ms per loop
>>> %timeit [j - i for i,j in zip(x1, x2)]
10 loops, best of 3: 38.2 ms per loop
使用 iterools.izip
(Python 2) 或简单地在 Python 3 中zip
将使列表理解版本几乎与 map
一样快:
>>> %timeit [j - i for i,j in izip(x1, x2)]
10 loops, best of 3: 20.5 ms per loop
>>> %timeit tuple(i-j for i,j in zip(x2,x1))
10 loops, best of 3: 40.5 ms per loop
>>> %timeit tuple(i-j for i,j in izip(x2,x1))
10 loops, best of 3: 25.1 ms per loop
#Numpy arrays
>>> %timeit x2_arr - x1_arr
1000 loops, best of 3: 469 µs per loop
zip
函数(创建一个迭代器,聚合每个可迭代对象的元素。
>>> tuple(i-j for i,j in zip(x2,x1))
(511L, 255L, 255L)
这是基本的:
>>> x1 =(2873120768L, 2873122560L, 2873123328L)
>>> x2 =(2873121279L, 2873122815L, 2873123583L)
>>> tuple( x2[i] - x1[i] for i in range(len(x1)))
(511L, 255L, 255L)
注意:假设 len(x1) 和 len(x2) 总是相同的
您可以在压缩值时使用 map/lambda
x1 =(2873120768L, 2873122560L, 2873123328L)
x2 =(2873121279L, 2873122815L, 2873123583L)
print map(lambda (x,y):y-x,zip(x1,x2) )