Python3 ValueError - 遍历列表时要解压的值太多
Python3 ValueError - Too many values to unpack while iterating over a list
这是一个简单的代码,旨在使用英语名字和姓氏列表生成全名列表:
names = """
Walter
Dave
Albert""".split()
fullnames = [(first + last) for first, last in names]
print(fullnames)
为了这个 post,我把 names
变小了,但我包含了 100 个名字。
输出:
Traceback (most recent call last):
File "/home/pussyslayer42069/Desktop/py/names.py", line 105, in <module>
fullnames = [(first + last) for first, last in names]
File "/home/pussyslayer42069/Desktop/py/names.py", line 105, in <listcomp>
fullnames = [(first + last) for first, last in names]
ValueError: too many values to unpack (expected 2)
使用zip
并遍历列表的两个部分
[(f, l) for f, l in zip(names[:-1], names[1:]]
如果我找到你,这就是解决方案;
names = """
Walter
Dave
Albert""".split()
fullnames = [(names[i] + ' ' + names[i + 1]) for i in range(len(names) - 1)]
print(fullnames)
这是一个简单的代码,旨在使用英语名字和姓氏列表生成全名列表:
names = """
Walter
Dave
Albert""".split()
fullnames = [(first + last) for first, last in names]
print(fullnames)
为了这个 post,我把 names
变小了,但我包含了 100 个名字。
输出:
Traceback (most recent call last):
File "/home/pussyslayer42069/Desktop/py/names.py", line 105, in <module>
fullnames = [(first + last) for first, last in names]
File "/home/pussyslayer42069/Desktop/py/names.py", line 105, in <listcomp>
fullnames = [(first + last) for first, last in names]
ValueError: too many values to unpack (expected 2)
使用zip
并遍历列表的两个部分
[(f, l) for f, l in zip(names[:-1], names[1:]]
如果我找到你,这就是解决方案;
names = """
Walter
Dave
Albert""".split()
fullnames = [(names[i] + ' ' + names[i + 1]) for i in range(len(names) - 1)]
print(fullnames)