-1

I am currently trying to re-sort a list I got from parsing a website.

I have tried everything but I don't think I found the best solution to my problem.

Let's say we have the following list:

my_list = [['a', 'b', 'c'], ['a', 'b', 'c']]

What I am trying to convert it to:

new_list = [['a', 'a'], ['b', 'b'], ['c', 'c']]

I came up with the following loop:

result = [[], [], []]

for sublist in my_list:
    for i in range(0, len(sublist)):
        result[i].append(sublist[i])
print(result)
# output: [['a', 'a'], ['b', 'b'], ['c', 'c']]

My method is not the best I assume and I am searching for the most pythonic way to do it if you know what I'm saying.

Morse
  • 8,258
  • 7
  • 39
  • 64
bantix
  • 58
  • 8

2 Answers2

0

The Python builtin function zip() is your friend here.

From the official documentation, it

returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

What that means is that given two lists, zip(list1, list2) will pair list1[0] with list2[0], list1[1] with list2[1], and so on.

In your case, the lists you want to zip together are inside another list, my_list, so you can unpack it with *my_list. Since zip() returns an iterator, you want to create a list out of the return value of zip(). Final solution:

new_list = list(zip(*my_list))
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
jeremye
  • 1,368
  • 9
  • 19
0

I have written a code which exactly does what you want. You should use map after zip to convert tuples to lists.

Code:

my_list = [['a', 'b', 'c'], ['a', 'b', 'c']]
my_new_list = list(map(list, zip(my_list[0], my_list[1])))
print(my_new_list)

Output:

>>> python3 test.py 
[['a', 'a'], ['b', 'b'], ['c', 'c']]
milanbalazs
  • 4,811
  • 4
  • 23
  • 45