Home >Backend Development >Python Tutorial >How to Transpose a List of Lists in Python?

How to Transpose a List of Lists in Python?

DDD
DDDOriginal
2024-12-20 02:45:10750browse

How to Transpose a List of Lists in Python?

Transpose a List of Lists

Given a list of lists, the goal is to transpose it, reversing the rows and columns. For instance, for the input:

l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

the desired output is:

r = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Python 3 Solutions:

  • Using zip and map:
list(map(list, zip(*l)))

This solution uses zip to iterate over the columns of the list and map to convert each column to a list.

  • Using zip_longest from itertools:
list(map(list, itertools.zip_longest(*l, fillvalue=None)))

This solution uses itertools.zip_longest, which works similarly to zip but includes a fillvalue parameter to fill in missing values when the lists are jagged.

Python 2 Solution:

map(list, zip(*l))

Explanation:

The zip function creates an iterator of tuples, where each tuple represents a column in the input list. By unpacking the argument list with *l, zip iterates over each column in parallel. The map function then converts each tuple to a list, producing the desired transposed list.

Note: Python 2's zip does not have the fillvalue parameter, so it will discard data if the lists are jagged.

The above is the detailed content of How to Transpose a List of Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn