How to unpack optional items from a tuple? [duplicate]

只谈情不闲聊 提交于 2021-02-04 17:57:05

问题


I have a list of some input values, of which the first couple of mandatory and the last couple optional. Is there any easy way to use tuple unpacking to assign these to variables, getting None if the optional parameters are missing.

eg.

a = [1,2]   
foo, bar, baz = a
# baz == None

ideally a could be any length - including longer than 3 (other items thrown away).

At the moment I'm using zip with a list of parameter names to get a dictionary:

items = dict(zip(('foo', 'bar', 'baz'), a))
foo = items.get('foo', None)
bar = items.get('bar', None)
baz = items.get('baz', None)

but it's a bit long-winded.


回答1:


From the linked question, this works:

foo, bar, baz == (list(a) + [None]*3)[:3]



回答2:


Use itertools.izip_longest:

from itertools import izip_longest
max_params = 3
args = (1, 2)

foo, bar, baz = zip(*izip_longest(args, range(max_params)))[0]

I should note that if you find yourself having to do this, though, you should probably consider storing the parameters in a dict instead of unpacking them into variables.

Update: Since you're stuck with 2.5, try the following:

max_params = 3
args = (1, 2)

def unpack(args, param_length):
    return args + tuple(None for _ in range(param_length - len(args)))

foo, bar, baz = unpack(args, max_params)



回答3:


What about using Try Except:

>>> a = [1,2]
>>> try:
...     foo, bar, baz = a
... except:
...     foo, bar = a
...
>>>


来源:https://stackoverflow.com/questions/21483301/how-to-unpack-optional-items-from-a-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!