Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何添加元组_Python_Algorithm_Tuples - Fatal编程技术网

Python 如何添加元组

Python 如何添加元组,python,algorithm,tuples,Python,Algorithm,Tuples,我有这样的伪代码: if( b < a) return (1,0)+foo(a-b,b) if(b

我有这样的伪代码:

if( b < a)
   return (1,0)+foo(a-b,b)
if(b

我想用python编写它。但是python可以添加元组吗?编写这样的代码的最佳方法是什么?

您想进行元素加法还是附加元组?默认情况下,python会这样做

(1,2)+(3,4) = (1,2,3,4)
您可以将自己的定义为:

def myadd(x,y):
     z = []
     for i in range(len(x)):
         z.append(x[i]+y[i])
     return tuple(z)
此外,正如@delnan的评论所明确指出的,这篇文章最好写为

def myadd(xs,ys):
     return tuple(x + y for x, y in izip(xs, ys))
甚至在功能上:

myadd = lambda xs,ys: tuple(x + y for x, y in izip(xs, ys))
那就做吧

if( b < a) return myadd((1,0),foo(a-b,b))
if(b
我会选择

>>> map(sum, zip((1, 2), (3, 4)))
[4, 6]
或者更自然地说:

>>> numpy.array((1, 2)) + numpy.array((3, 4))
array([4, 6])
与highBandWidth的答案相反,这种方法要求元组在Python2.7或更早版本中具有相同的长度,而不是引发TypeError。在Python3中,
map
略有不同,因此结果是长度等于
a
b
中较短者的和的元组

如果需要Python 2中的截断行为,可以将
map
替换为
itertools.imap

tuple(itertools.imap(operator.add, a, b))

如果希望
+
本身以这种方式工作,可以将
tuple子类化,并覆盖添加:

class mytup(tuple):
    def __add__(self, other):
        if len(self) != len(other):
             return NotImplemented # or raise an error, whatever you prefer
         else:
             return mytup(x+y for x,y in izip(self,other))
同样的情况也适用于
\uuuu sub\uuuuuu
\uuu mul\uuuu
\uu div\uuuuuu
\uu gt\uuuuuuuuuu
等。有关这些特殊运算符的更多信息,请参见和


您仍然可以通过调用原始元组加法来追加元组:
tuple.\uuuu add\uuu(a,b)
而不是
a+b
。或者在新类中定义一个
append()
函数来实现这一点。

元组(x+y代表x,y在izip(xs,ys))中)
。确切地说,我想做一些类似“myadd”的事情,这是最好的方法?是的,delnan的注释更简洁。如果元组的长度不同,您的
myadd
将自动将较长元组的长度截断为较短元组的长度。这可能是一个问题,也可能不是问题。确实要挖掘样式,但确实需要另一个导入。works-但是对于微小的代码来说,必须导入numpy可能会有点过头。
class mytup(tuple):
    def __add__(self, other):
        if len(self) != len(other):
             return NotImplemented # or raise an error, whatever you prefer
         else:
             return mytup(x+y for x,y in izip(self,other))