Input is [[159,159],[21,21]]
and I need
output like [[159,21],[159,21]]
I have searched python solution and tried a lot still am not getting solution, please share me solution.
Input is [[159,159],[21,21]]
and I need
output like [[159,21],[159,21]]
I have searched python solution and tried a lot still am not getting solution, please share me solution.
zip
will do just that:
lst = [[159, 159], [21, 21]]
lst2 = list(zip(*lst))
print(lst2) # [(159, 21), (159, 21)]
if you need the nested elements to be lists as well:
lst2 = [list(item) for item in zip(*lst)] # [[159, 21], [159, 21]]
Steps
zip
the data togethermap
Code
data = [[159,159],[21,21]]
print(list(map(list, zip(data[0],data[1]))))
Output
[[159,21],[159,21]]
You can use zip
:
in_lists = [[159,159], [21,21]]
out_lists = list(zip(*in_lists))
print(out_lists)
which outputs
[(159, 21), (159, 21)]
The *
in zip(*in_lists)
will "unpack" the iterator in_lists
and feed them to zip
as separate arguments, which will be like zip([159, 159], [21, 21])
. The zip
function then combines the i-th element from all iterables into tuples, which results in [(159, 21), (159, 21)]
.