简体   繁体   中英

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.

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

[(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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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