[英]Python element-wise tuple operations like sum
無論如何要讓 Python 中的元組操作像這樣工作:
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
代替:
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
我知道它是這樣工作的,因為__add__
和__mul__
方法被定義為這樣工作。 那么唯一的方法就是重新定義它們?
import operator
tuple(map(operator.add, a, b))
使用所有內置插件..
tuple(map(sum, zip(a, b)))
此解決方案不需要導入:
tuple(map(lambda x, y: x + y, tuple1, tuple2))
有點結合前兩個答案,對鐵蛙的代碼進行調整,使其返回一個元組:
import operator
class stuple(tuple):
def __add__(self, other):
return self.__class__(map(operator.add, self, other))
# obviously leaving out checking lengths
>>> a = stuple([1,2,3])
>>> b = stuple([3,2,1])
>>> a + b
(4, 4, 4)
注意:使用self.__class__
而不是stuple
來簡化子類化。
from numpy import array
a = array( [1,2,3] )
b = array( [3,2,1] )
print a + b
給出array([4,4,4])
。
可以使用生成器理解來代替地圖。 內置的 map 函數並沒有過時,但對於大多數人來說,它的可讀性比 list/generator/dict comprehension 要差,所以我建議一般不要使用 map 函數。
tuple(p+q for p, q in zip(a, b))
所有發電機解決方案。 不確定性能(不過 itertools 很快)
import itertools
tuple(x+y for x, y in itertools.izip(a,b))
沒有返回元組的類定義的簡單解決方案
import operator
tuple(map(operator.add,a,b))
更簡單,不使用地圖,你可以做到
>>> tuple(sum(i) for i in zip((1, 2, 3), (3, 2, 1)))
(4, 4, 4)
是的。 但是你不能重新定義內置類型。 你必須對它們進行子類化:
class MyTuple(tuple): def __add__(self, other): if len(self) != len(other): raise ValueError("tuple lengths don't match") return MyTuple(x + y for (x, y) in zip(self, other))
我目前對“元組”類進行子類化以重載 +、- 和 *。 我發現它使代碼更漂亮,編寫代碼更容易。
class tupleN(tuple):
def __add__(self, other):
if len(self) != len(other):
return NotImplemented
else:
return tupleN(x+y for x,y in zip(self,other))
def __sub__(self, other):
if len(self) != len(other):
return NotImplemented
else:
return tupleN(x-y for x,y in zip(self,other))
def __mul__(self, other):
if len(self) != len(other):
return NotImplemented
else:
return tupleN(x*y for x,y in zip(self,other))
t1 = tupleN((1,3,3))
t2 = tupleN((1,3,4))
print(t1 + t2, t1 - t2, t1 * t2, t1 + t1 - t1 - t1)
(2, 6, 7) (0, 0, -1) (1, 9, 12) (0, 0, 0)
如果您已經在使用numpy
這是另一個方便的解決方案。 它很緊湊,加法運算可以用任何numpy 表達式替換。
import numpy as np
tuple(np.array(a) + b)
我一直回到這個問題,我並不特別喜歡任何答案,因為它們都在回答一般情況的問題,而且我通常正在尋找特殊情況的答案:我通常使用固定的元組計數,例如 n 維。
# eg adding a dx/dy to an xy point.
# if I have a point xy and another point dxdy
x, y = xy
dx, dy = dxdy
return x+dx, y+dy
雖然我通常對不必要的變量感到不寒而栗,但我解包元組的原因通常是因為我將元素作為個體處理,這就是上面要求的元組添加所發生的情況。
如果有人需要對元組列表求平均值:
import operator
from functools import reduce
tuple(reduce(lambda x, y: tuple(map(operator.add, x, y)),list_of_tuples))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.