0

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.

smci
  • 32,567
  • 20
  • 113
  • 146
Sindhu M
  • 17
  • 2
  • 3
    "tried a lot ": perhaps share your best efforts, and try and indicate where you got stuck. – 9769953 Apr 27 '22 at 09:58
  • 1
    Have you tried working with the `zip()` function? – 9769953 Apr 27 '22 at 09:59
  • This is a duplicate, there are 185 Q&A on [\[python\] zip nested lists](https://stackoverflow.com/search?q=%5Bpython%5D+zip+nested+lists) – smci Apr 27 '22 at 10:24

3 Answers3

0

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]]
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0

Steps

  1. zip the data together
  2. convert the zipped tuple to list using map
  3. convert the whole thing to be a list

Code

data = [[159,159],[21,21]]
print(list(map(list, zip(data[0],data[1]))))

Output

[[159,21],[159,21]]
holydragon
  • 6,158
  • 6
  • 39
  • 62
0

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

Tom Aarsen
  • 1,170
  • 2
  • 20