0

Convert

mylist = [['Taiwan', 'Japan', 'Korea'], [18, 30, 20], ['False', 'True', 'False'], [1, 2, 3]]

To

newlist = [['Taiwan', 18, 'False', 1], ['Japan', 30, 'True', 'False', 2], ['Korea', 20, 'False', 3]]

I tried to use a for to solve it:

for i in range(len(mylist)):
    for j in mylist:
        print(j[i])

But I didnt get the expected result:

Taiwan

I don't know how to do? Please help.

Right leg
  • 16,080
  • 7
  • 48
  • 81
BryanL
  • 35
  • 4

4 Answers4

4

You can use zip for that:

mylist = [list(i) for i in zip(*mylist)]

mylist:

[['Taiwan', 18, 'False', 1], ['Japan', 30, 'True', 2], ['Korea', 20, 'False', 3]]
LeoE
  • 2,054
  • 1
  • 11
  • 29
2

Use this one-liner:

>>> [[item[j] for item in mylist] for j in range(len(mylist[0]))]
[['Taiwan', 18, 'False', 1],
 ['Japan', 30, 'True', 2],
 ['Korea', 20, 'False', 3]]
CDJB
  • 14,043
  • 5
  • 29
  • 55
2

Just use zip!

>>> list(zip(*mylist))
[('Taiwan', 18, 'False', 1), ('Japan', 30, 'True', 2), ('Korea', 20, 'False', 3)]
Shubham Sharma
  • 714
  • 1
  • 8
  • 18
1

You can use zip for this

zip(*mylist)

and it gives list of set

for list of lit use,

[list(i) for i in zip(*mylist)]
Khakhar Shyam
  • 459
  • 2
  • 11