Python函数参数:tuple / list [英] Python function parameter: tuple/list
问题描述
我的函数需要一个列表或一个元组作为参数。它不是真正关心它是什么,它所做的是将它传递给另一个接受列表或元组的函数:
def func(arg):#arg is tuple or list
another_func(x)
#do other stuff here
现在我需要稍微修改函数,以处理一个额外的元素:
def func (arg):#arg is tuple or list
another_func(x + ['a'])
#etc
$ b不幸的是这不会工作:如果arg是元组,我必须说 x +('a',)
。
显然,我可以通过强制arg列表来使它工作。但它不整洁。
有更好的方法吗?
如果我们不能通过一个元组, another_func
只是想要一个迭代器,你可以传递 itertools.chain(x,'a')
>
My function expects a list or a tuple as a parameter. It doesn't really care which it is, all it does is pass it to another function that accepts either a list or tuple:
def func(arg): # arg is tuple or list
another_func(x)
# do other stuff here
Now I need to modify the function slightly, to process an additional element:
def func(arg): #arg is tuple or list
another_func(x + ['a'])
# etc
Unfortunately this is not going to work: if arg is tuple, I must say x + ('a',)
.
Obviously, I can make it work by coercing arg to list. But it isn't neat.
Is there a better way of doing that? I can't force callers to always pass a tuple, of course, since it simply shifts to work to them.
If another_func
just wants a iterable you can pass itertools.chain(x,'a')
to it.
这篇关于Python函数参数:tuple / list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!