如何添加元组 [英] How to add with tuples

查看:205
本文介绍了如何添加元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的伪代码:

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

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

I want to write it in python. But can python add tuples? What is the best way to code something like that?

推荐答案

您要对元素进行加法还是要附加元组?默认情况下python会

Do you want to do element-wise addition, or to append the tuples? By default python does

(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's注释清楚了,最好写成这样

Also, as @delnan's comment makes it clear, this is better written as

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

这篇关于如何添加元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆