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])])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With