عمليات الصفوف من حيث العناصر في بايثون مثل sum

StackOverflow https://stackoverflow.com/questions/497885

  •  20-08-2019
  •  | 
  •  

سؤال

هل هناك أي طريقة للحصول على عمليات tuple في 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))

تم جمع نوعي الإجابات الأولين ، مع قرص إلى رمز Ironfroggy بحيث يعيد tuple:

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 *

a = array( [1,2,3] )
b = array( [3,2,1] )

print a + b

يعطي array([4,4,4]).

نرى http://www.scipy.org/tentative_numpy_tutorial

يمكن استخدام فهم المولد بدلاً من الخريطة. وظيفة الخريطة المدمجة ليست عفا عليها الزمن ولكنها أقل قابلية للقراءة بالنسبة لمعظم الناس من فهم القائمة/المولد/التصميم ، لذلك أوصي بعدم استخدام وظيفة الخريطة بشكل عام.

tuple(p+q for p, q in zip(a, b))

حل بسيط دون تعريف الفئة الذي يرجع tuple

import operator
tuple(map(operator.add,a,b))

كل حل المولد. لست متأكدًا من الأداء (Itertools سريع ، رغم ذلك)

import itertools
tuple(x+y for x, y in itertools.izip(a,b))

نعم. لكن لا يمكنك إعادة تعريف الأنواع المدمجة. عليك أن تصاعدهم:

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))

حتى أبسط وبدون استخدام الخريطة ، يمكنك القيام بذلك

>>> tuple(sum(i) for i in zip((1, 2, 3), (3, 2, 1)))
(4, 4, 4)

أنا حاليا فئة فرعية فئة "tuple" إلى الزائد +،- و *. أجد أنه يجعل الكود جميلًا وكتابة الرمز أسهل.

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)

في حالة احتياج شخص ما إلى حساب متوسط ​​قائمة المجموعات:

import operator 
from functools import reduce
tuple(reduce(lambda x, y: tuple(map(operator.add, x, y)),list_of_tuples))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top