简体   繁体   English

Python3 ValueError - 迭代列表时解包的值太多

[英]Python3 ValueError - Too many values to unpack while iterating over a list

This is a simple code meant to generate a list of full names using a list of English first and surnames:这是一个简单的代码,旨在使用英语名字和姓氏列表生成全名列表:

names = """
Walter
Dave
Albert""".split()

fullnames = [(first + last) for first, last in names]
print(fullnames)

I made names smaller just for the sake of this post, but I included 100 names.为了这篇文章,我把names变小了,但我包括了 100 个名字。

output: output:

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)

Use zip and iterate over two slices of the list使用zip并遍历列表的两个切片

[(f, l) for f, l in zip(names[:-1], names[1:]]

If i got you, here is the solution;如果我得到你,这是解决方案;

names = """
Walter
Dave
Albert""".split()


fullnames = [(names[i] + ' ' + names[i + 1]) for i in range(len(names) - 1)]
print(fullnames)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM