如何解包元素数量未知的列表并将未匹配变量自动赋值为None
方法1:补全列表后直接解包
先把原列表补全到你需要的变量个数,不足的位置填充None,再直接解包赋值即可:
tags = ["ff", "uu", "ss"] # 补全到5个元素,超出5个的话默认只取前5个 tag1, tag2, tag3, tag4, tag5 = tags[:5] + [None] * max(0, 5 - len(tags))
运行后对应结果:
- tag1 = "ff"
- tag2 = "uu"
- tag3 = "ss"
- tag4 = None
- tag5 = None
如果能确定原列表长度不会超过变量个数,可以简化写法:
tag1, tag2, tag3, tag4, tag5 = tags + [None] * (5 - len(tags))
方法2:用迭代器逐个取值
把列表转成迭代器后,用next()方法逐个取值,取不到的时候默认返回None:
tags = ["ff", "uu", "ss"] it = iter(tags) tag1 = next(it, None) tag2 = next(it, None) tag3 = next(it, None) tag4 = next(it, None) tag5 = next(it, None)
这个方法不需要提前计算列表长度,也不会生成额外的补全列表,适合原列表体积较大、或者需要赋值的变量数量较多的场景。
内容的提问来源于stack exchange,提问作者amine ami
相关产品推荐
相关产品推荐

