Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: too many values to unpack: python list manipulation

Tags:

python

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


2 Answers

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)]
like image 184
NPE Avatar answered Apr 20 '26 20:04

NPE


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])])
like image 28
Andrej Kesely Avatar answered Apr 20 '26 19:04

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!