包含长数的两个元组的差异

时间:2014-11-14 21:05:23

标签: python performance tuples

我有两个Long值的元组。我需要它们的区别,例如x2-x1

x1 =
(2873120768, 2873122560, 2873123328)
x2 =
(2873121279, 2873122815, 2873123583)

预期结果:

result = (511,255,255)

但是它是元组还是列表无关紧要

我正在寻找一种方法,如果可能的话,不要逐个元素地去做。速度是一个约束。我搜索了它,但无法找到答案。

提前谢谢

5 个答案:

答案 0 :(得分:4)

你可以zip元组,迭代对,并在列表理解中执行减法。

>>> x1 = (2873120768, 2873122560, 2873123328)
>>> x2 = (2873121279, 2873122815, 2873123583)
>>> [j - i for i,j in zip(x1,x2)]
[511, 255, 255]

答案 1 :(得分:3)

您可以使用zip函数(创建一个聚合来自每个迭代的元素的迭代器。):

>>> tuple(i-j for i,j in zip(x2,x1))
(511L, 255L, 255L)

答案 2 :(得分:3)

在纯Python中,最快的方法是将mapoperator.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

在Python 3中使用iterools.izip(Python 2)或简单地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

答案 3 :(得分:1)

这里是基本的:

>>> 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)始终相同

答案 4 :(得分:0)

您可以在压缩值时使用map / lambda

x1 =(2873120768L, 2873122560L, 2873123328L)
x2 =(2873121279L, 2873122815L, 2873123583L)
print map(lambda (x,y):y-x,zip(x1,x2) )