user9703788
user9703788

Reputation:

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

Upvotes: 2

Views: 134

Answers (3)

hygull
hygull

Reputation: 8740

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]]
>>>

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195553

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])])

Upvotes: 1

NPE
NPE

Reputation: 500773

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)]

Upvotes: 6

Related Questions