python 从相同长度的元组添加值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1169725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:38:27  来源:igfitidea点击:

Adding Values From Tuples of Same Length

python

提问by Keegan Jay

In a graphical program I'm writing using pygame I use a tuple representing a coordinate like this: (50, 50).

在我使用 pygame 编写的图形程序中,我使用一个元组来表示这样的坐标:(50, 50)。

Sometimes, I call a function which returns another tuple such as (3, -5), which represents the change in coordinate.

有时,我调用一个函数,该函数返回另一个元组,例如 (3, -5),表示坐标的变化。

What is the best way to add the change value to the coordinate value. It would be nice if I could do something like coordinate += change, but it appears that would simply concatenate the two tuples to something like (50, 50, 3, -5). Rather than adding the 1st value to the 1st value and the 2nd to the 2nd, and returning a resulting tuple.

将更改值添加到坐标值的最佳方法是什么。如果我能做一些像坐标 += 改变这样的事情会很好,但它似乎只是将两个元组连接到像 (50, 50, 3, -5) 这样的东西。而不是将第一个值添加到第一个值并将第二个值添加到第二个值,并返回结果元组。

Until now I've been using this rather tiresome method: coord = (coord[0] + change[0], coord[1] + change[1])

到目前为止,我一直在使用这种相当烦人的方法: coord = (coord[0] + change[0], coord[1] + change[1])

What is a better, more concise method to add together the values of two tuples of the same length. It seems especially important to know how to do it if the tuples are of an arbitrary length or a particularly long length that would make the previous method even more tiresome.

将两个相同长度的元组的值加在一起的更好、更简洁的方法是什么?如果元组具有任意长度或特别长的长度,这将使之前的方法更加令人厌烦,那么知道如何执行此操作似乎尤为重要。

回答by John Y

Well, one way would be

嗯,一种方法是

coord = tuple(sum(x) for x in zip(coord, change))

If you are doing a lot of math, you may want to investigate using NumPy, which has much more powerful array support and better performance.

如果您正在做大量数学运算,您可能想使用NumPy进行调查,它具有更强大的数组支持和更好的性能。

回答by Triptych

List comprehension is probably more readable, but here's another way:

列表理解可能更具可读性,但这是另一种方式:

>>> a = (1,2)
>>> b = (3,4)
>>> tuple(map(sum,zip(a,b)))
(4,6)

回答by Pradeep

This is a work in progress as I am learning Python myself. Can we use classes here, could simplify some operations later. I propose to use a coord class to store the coordinates. It would override add and sub so you could do addition and subtraction by simply using operators + and -. You could get the tuple representation with a function built into it.

这是一项正在进行的工作,因为我正在学习 Python。这里可以使用类吗,以后可以简化一些操作。我建议使用 coord 类来存储坐标。它会覆盖 add 和 sub,因此您可以通过简单地使用运算符 + 和 - 来进行加法和减法。您可以获得带有内置函数的元组表示。

Class

班级

class coord(object):    
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def __add__(self,c):
        return coord(self.x + c.x, self.y + c.y)

    def __sub__(self,c):
        return coord(self.x - c.x, self.y - c.y)

    def __eq__(self,c): #compares two coords
        return self.x == c.x and self.y == c.y

    def t(self): #return a tuple representation.
        return (self.x,self.y)

Usage

用法

c1 = coord(4,3) #init coords
c2 = coord(3,4)

c3 = c1 + c2    #summing two coordinates. calls the overload __add__
print c3.t()    #prints (7, 7)
c3 = c3 - c1
print c3.t()    #prints (3, 4)
print c3 == c2  #prints True

you could improve coord to extend other operators as well (less than, greater than ..).

您也可以改进坐标以扩展其他运算符(小于、大于 ..)。

In this version after doing your calculations you can call the pygame methods expecting tuples by just saying coord.t(). There might be a better way than have a function to return the tuple form though.

在此版本中,在完成计算后,您只需说 coord.t() 即可调用需要元组的 pygame 方法。不过,可能有比返回元组形式的函数更好的方法。

回答by mhawke

To get your "+" and "+=" behaviour you can define your own class and implement the __add__()method. The following is an incomplete sample:

要获得“+”和“+=”行为,您可以定义自己的类并实现该__add__()方法。以下是一个不完整的样本:

# T.py
class T(object):
    def __init__(self, *args):
        self._t = args
    def __add__(self, other):
        return T(*([sum(x) for x in zip(self._t, other._t)]))
    def __str__(self):
        return str(self._t)
    def __repr__(self):
        return repr(self._t)

>>> from T import T
>>> a = T(50, 50)
>>> b = T(3, -5)
>>> a
(50, 50)
>>> b
(3, -5)
>>> a+b
(53, 45)
>>> a+=b
>>> a
(53, 45)
>>> a = T(50, 50, 50)
>>> b = T(10, -10, 10)
>>> a+b
(60, 40, 60)
>>> a+b+b
(70, 30, 70)

EDIT: I've found a better way...

编辑:我找到了更好的方法......

Define class T as a subclass of tuple and override the __new__and __add__methods. This provides the same interface as class tuple(but with different behaviour for __add__), so instances of class T can be passed to anything that expects a tuple.

将类 T 定义为 tuple 的子类并覆盖__new____add__方法。这提供了与类相同的接口tuple(但对于 具有不同的行为__add__),因此类 T 的实例可以传递给任何需要元组的东西。

class T(tuple):
    def __new__(cls, *args):
        return tuple.__new__(cls, args)
    def __add__(self, other):
        return T(*([sum(x) for x in zip(self, other)]))
    def __sub__(self, other):
        return self.__add__(-i for i in other)

>>> a = T(50, 50)
>>> b = T(3, -5)
>>> a
(50, 50)
>>> b
(3, -5)
>>> a+b
(53, 45)
>>> a+=b
>>> a
(53, 45)
>>> a = T(50, 50, 50)
>>> b = T(10, -10, 10)
>>> a+b
(60, 40, 60)
>>> a+b+b
(70, 30, 70)
>>> 
>>> c = a + b
>>> c[0]
60
>>> c[-1]
60
>>> for x in c:
...     print x
... 
60
40
60

回答by Tom Roth

As John Y mentions, this is pretty easy using numpy.

正如 John Y 所提到的,使用 numpy 这很容易。

import numpy as np

x1 = (0,3)
x2 = (4,2)
tuple(np.add(x1,x2))

回答by sunqiang

My two cents, hope this helps

我的两分钱,希望这有帮助

>>> coord = (50, 50)
>>> change = (3, -5)
>>> tuple(sum(item) for item in zip(coord, change))
(53, 45)