如何将iterable解压缩为不匹配的变量数?
太多的价值观:
>>> one,two = [1,2,3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)可以忽略
>>> one,two,*_ = [1,2,3,4]
>>> 注意:"扩展可迭代解包装“只适用于Python3。关于下划线。
数据太少/变量过多的相反情况是如何做到的:
>>> one,two,three = [1,2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
>>>被处理,特别是使剩余的变量被赋值为None (或其他值)?
就像这样:
>>> one,two,three = [1,2] or None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
>>>
https://stackoverflow.com/a/8857846/1619432建议扩大列表:
>>> one,two,three = [1,2] + [None]*(3-2)
>>> one
1
>>> two
2
>>> three
>>>发布于 2019-12-12 11:14:51
使用*操作符,用正在解压缩的内容填充中间可迭代的内容,并用选择的默认值填充剩余部分。
x = [1, 2]
default_value= None
one, two, three = [*x, *([default_value] * (3 - len(x)))]以及处理这两起案件的奖金职能:
def unpack(source, target, default_value=None):
n = len(source)
if n < target:
return [*source, *([default_value] * (target - len(source)))]
elif n > target:
return source[0:target]
else:
return source根据需要修改以处理不可迭代的输入。
发布于 2019-12-12 11:15:04
可以使用以下方法将序列解压缩为三个变量:
one, two, *three = [1,2]此时,three将是一个空列表。然后,如果three为空,则可以使用or检查将or分配给or。
three = three or None发布于 2019-12-12 11:16:59
这个对你有用吗?您可以根据需要使nones数组大小。
nones = [None]*100 # or however many you think you might need
one, two, three, four, five, *_ = [1,2] + noneshttps://stackoverflow.com/questions/59303232
复制相似问题