Reputation: 9
I am trying to create a function that can do this.
>>> rearrange_list([1,2,3],[4,5,6])
[[1,4],[2,5],[3,6]]
So far what I have is
def rearrange_list(my_list):
i = 0
n = 0
new_list = []
for i in range(0, len(my_list[n])):
for n in range(0,len(my_list)):
new_list += [my_list[n][i]]
print(new_list)
n += 1
return new_list
but this code returns [1, 4, 2, 5, 3, 6]
, a single list instead of
a list of lists like I want it to and I can't seem to figure out how to make the
function output a list of lists based on the index of the list inside the list.
Upvotes: 0
Views: 149
Reputation:
You can use zip
and a list comprehension:
>>> def rearrange_lists(a, b):
... return [list(x) for x in zip(a, b)]
...
>>> rearrange_lists([1,2,3], [4,5,6])
[[1, 4], [2, 5], [3, 6]]
>>>
Note that the above function only handles two lists. If you want to handle any number of lists, you can use this:
>>> def rearrange_lists(*lsts):
... return [list(x) for x in zip(*lsts)]
...
>>> rearrange_lists([1,2,3], [4,5,6], [7,8,9])
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
>>>
Upvotes: 1
Reputation: 1121524
Use zip()
instead:
>>> zip([1,2,3], [4,5,6])
[(1, 4), (2, 5), (3, 6)]
or, for your specific varargs version:
>>> lsts = ([1,2,3], [4,5,6])
>>> zip(*lsts)
[(1, 4), (2, 5), (3, 6)]
or map the results to lists if tuples won't do:
map(list, zip([1,2,3], [4,5,6])) # Python 2
[list(t) for t in zip([1,2,3], [4,5,6])] # Python 2 and 3
As a replacement for your function:
def rearrange_list(*my_lists):
return [list(t) for t in zip(*my_lists)]
Upvotes: 0