简体   繁体   中英

ValueError: too many values to unpack: python list manipulation

I have a list in python

l= [[1105.46, 1105.75, 1105.75, 1105.46, 1051.46],
 [ 120.23,  120.23,  120.41,  20.41,  120.23]]

how can i get this one:

answer = [[1105.46,120.23], ....[1051.46,120.23]]

i did as:

answer = [[x, y] for x, y in l]
print answer

ValueError: too many values to unpack

Here is one simple way:

>>> map(list, zip(*l))
[[1105.46, 120.23], [1105.75, 120.23], [1105.75, 120.41], [1105.46, 20.41], [1051.46, 120.23]]

If you don't care whether the nested elements are lists or tuples, it's even simpler:

>>> zip(*l)
[(1105.46, 120.23), (1105.75, 120.23), (1105.75, 120.41), (1105.46, 20.41), (1051.46, 120.23)]

Use zip() function from standard python:

l= [[1105.46, 1105.75, 1105.75, 1105.46, 1051.46],
 [ 120.23,  120.23,  120.41,  20.41,  120.23]]

new_list = []
for x, y in zip(l[0], l[1]):
    new_list.append([x, y])

print(new_list)

Output:

[[1105.46, 120.23], [1105.75, 120.23], [1105.75, 120.41], [1105.46, 20.41], [1051.46, 120.23]]

One line version with list comprehension:

print([[x, y] for x, y in zip(l[0], l[1])])

You can also try the below approach.

>>> l = [[1105.46, 1105.75, 1105.75, 1105.46, 1051.46], [ 120.23,  120.23,  120.41,  20.41,  120.23]]
>>>
>>> answer = [list(tup) for tup in zip(*l)]
>>>
>>> answer
[[1105.46, 120.23], [1105.75, 120.23], [1105.75, 120.41], [1105.46, 20.41], [1051.46, 120.23]]
>>>

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