当可能没有足够的值来解包时,将列表值干净地分配给多个变量
Cleanly assign list values to multiple variables when there may not be enough values to unpack
例如,如果我想从l = [1,2,3,4,5]
分配a, b, c
,我可以做
a, b, c = l[:3]
但是如果 l
只是 [1,2]
(或 [1]
或 []
)怎么办?
有没有办法自动将其余变量设置为 None
或 ''
或 0
或其他一些默认值?
我考虑过在分配之前使用默认值扩展列表以匹配变量的数量,但只是想知道是否有更好的方法。
一般来说,要将大小为 M 的列表中的 N 个元素解压缩为 N 个单独的变量,其中 M <= N,然后您可以将列表切片填充到 N 并再次切片:
l = [1,]
a, b, c = (l[:3] + [None]*3)[:3]
a, b, c
# 1, None, None
如果您喜欢干净的 generator-based 方法,这也行得通:
from itertools import islice, cycle, chain
def pad(seq, filler=None):
yield from chain(seq, cycle([filler]))
a, b, c = islice(pad([1, ]), 3)
a, b, c
# 1, None, None
例如,如果我想从l = [1,2,3,4,5]
分配a, b, c
,我可以做
a, b, c = l[:3]
但是如果 l
只是 [1,2]
(或 [1]
或 []
)怎么办?
有没有办法自动将其余变量设置为 None
或 ''
或 0
或其他一些默认值?
我考虑过在分配之前使用默认值扩展列表以匹配变量的数量,但只是想知道是否有更好的方法。
一般来说,要将大小为 M 的列表中的 N 个元素解压缩为 N 个单独的变量,其中 M <= N,然后您可以将列表切片填充到 N 并再次切片:
l = [1,]
a, b, c = (l[:3] + [None]*3)[:3]
a, b, c
# 1, None, None
如果您喜欢干净的 generator-based 方法,这也行得通:
from itertools import islice, cycle, chain
def pad(seq, filler=None):
yield from chain(seq, cycle([filler]))
a, b, c = islice(pad([1, ]), 3)
a, b, c
# 1, None, None