Let’s take:
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The result I’m looking for is
r = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
and not
r = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Python 3:
Python 2:
Explanation:
There are two things we need to know to understand what’s going on:
zip(*iterables)This meanszipexpects an arbitrary number of arguments each of which must be iterable. E.g.zip([1, 2], [3, 4], [5, 6]).args,f(*args)will callfsuch that each element inargsis a separate positional argument off.itertools.zip_longestdoes not discard any data if the number of elements of the nested lists are not the same (homogenous), and instead fills in the shorter nested lists then zips them up.Coming back to the input from the question
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],zip(*l)would be equivalent tozip([1, 2, 3], [4, 5, 6], [7, 8, 9]). The rest is just making sure the result is a list of lists instead of a list of tuples.