问题:转置列表清单

让我们来:

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

我正在寻找的结果是

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

并不是

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

非常感激

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)]

Much appreciated


回答 0

怎么样

map(list, zip(*l))
--> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

对于python 3.x,用户可以使用

list(map(list, zip(*l)))

说明:

我们需要了解两件事以了解正在发生的事情:

  1. zip的签名:zip(*iterables)这意味着zip需要任意数量的参数,每个参数必须是可迭代的。例如zip([1, 2], [3, 4], [5, 6])
  2. 未打包的参数列表:给定一个参数序列argsf(*args)将调用f使得每个元素args是一个单独的位置参数f

回到问题的输入l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]zip(*l)将等效于zip([1, 2, 3], [4, 5, 6], [7, 8, 9])。剩下的只是确保结果是列表列表而不是元组列表。

How about

map(list, zip(*l))
--> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

For python 3.x users can use

list(map(list, zip(*l))) # short circuits at shortest nested list if table is jagged
list(map(list, itertools.zip_longest(*l, fillvalue=None))) # discards no data if jagged and fills short nested lists with None

Explanation:

There are two things we need to know to understand what’s going on:

  1. The signature of zip: zip(*iterables) This means zip expects an arbitrary number of arguments each of which must be iterable. E.g. zip([1, 2], [3, 4], [5, 6]).
  2. Unpacked argument lists: Given a sequence of arguments args, f(*args) will call f such that each element in args is a separate positional argument of f.
  3. itertools.zip_longest does 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 to zip([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.


回答 1

一种方法是使用NumPy转置。有关列表,请:

>>> import numpy as np
>>> np.array(a).T.tolist()
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

或另一个没有拉链的人:

>>> map(list,map(None,*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

One way to do it is with NumPy transpose. For a list, a:

>>> import numpy as np
>>> np.array(a).T.tolist()
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Or another one without zip:

>>> map(list,map(None,*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

回答 2

等效于耶拿的解决方案:

>>> l=[[1,2,3],[4,5,6],[7,8,9]]
>>> [list(i) for i in zip(*l)]
... [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Equivalently to Jena’s solution:

>>> l=[[1,2,3],[4,5,6],[7,8,9]]
>>> [list(i) for i in zip(*l)]
... [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

回答 3

只是为了好玩,有效的矩形并假设存在m [0]

>>> m = [[1,2,3],[4,5,6],[7,8,9]]
>>> [[row[i] for row in m] for i in range(len(m[0]))]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

just for fun, valid rectangles and assuming that m[0] exists

>>> m = [[1,2,3],[4,5,6],[7,8,9]]
>>> [[row[i] for row in m] for i in range(len(m[0]))]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

回答 4

方法1和2在Python 2或3中工作,并且在粗糙的矩形 2D列表中工作。这意味着内部列表的长度不必彼此相同(参差不齐),也可以不必与外部列表的长度相同(矩形)。其他方法,很复杂。

设置

import itertools
import six

list_list = [[1,2,3], [4,5,6, 6.1, 6.2, 6.3], [7,8,9]]

方法1 — map()zip_longest()

>>> list(map(list, six.moves.zip_longest(*list_list, fillvalue='-')))
[[1, 4, 7], [2, 5, 8], [3, 6, 9], ['-', 6.1, '-'], ['-', 6.2, '-'], ['-', 6.3, '-']]

six.moves.zip_longest() 变成

默认填充值为None。感谢@jena的answer,其中map()将内部元组更改为列表。在这里它将迭代器变成列表。感谢@Oregano和@badp的评论

在Python 3中,将结果传递通过list()以获得与方法2相同的2D列表。


方法2 –列表理解 zip_longest()

>>> [list(row) for row in six.moves.zip_longest(*list_list, fillvalue='-')]
[[1, 4, 7], [2, 5, 8], [3, 6, 9], ['-', 6.1, '-'], ['-', 6.2, '-'], ['-', 6.3, '-']]

@ inspectorG4dget替代


方法3 – map()map()在Python 3.6破

>>> map(list, map(None, *list_list))
[[1, 4, 7], [2, 5, 8], [3, 6, 9], [None, 6.1, None], [None, 6.2, None], [None, 6.3, None]]

第二种选择非常紧凑@SiggyF,适用于参差不齐的 2D列表,与他的第一个使用numpy进行转置并通过参差不齐的列表的代码不同。但是,没有一个必须是填充值。(不,传递给内部map()的None不是填充值。这意味着没有处理每一列的功能。这些列只是传递给外部map(),后者将它们从元组转换为列表。

在Python 3中的某个地方,map()不再忍受所有这种滥用:第一个参数不能为None,并且衣衫it的迭代器只会被截短到最短。其他方法仍然有效,因为这仅适用于内部map()。


方法4 – map()map()重新

>>> list(map(list, map(lambda *args: args, *list_list)))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]   // Python 2.7
[[1, 4, 7], [2, 5, 8], [3, 6, 9], [None, 6.1, None], [None, 6.2, None], [None, 6.3, None]] // 3.6+

遗憾的是,在Python 3中,行行变得不成为行列,它们只是被截断了。嘘声进步。

Methods 1 and 2 work in Python 2 or 3, and they work on ragged, rectangular 2D lists. That means the inner lists do not need to have the same lengths as each other (ragged) or as the outer lists (rectangular). The other methods, well, it’s complicated.

the setup

import itertools
import six

list_list = [[1,2,3], [4,5,6, 6.1, 6.2, 6.3], [7,8,9]]

method 1 — map(), zip_longest()

>>> list(map(list, six.moves.zip_longest(*list_list, fillvalue='-')))
[[1, 4, 7], [2, 5, 8], [3, 6, 9], ['-', 6.1, '-'], ['-', 6.2, '-'], ['-', 6.3, '-']]

six.moves.zip_longest() becomes

The default fillvalue is None. Thanks to @jena’s answer, where map() is changing the inner tuples to lists. Here it is turning iterators into lists. Thanks to @Oregano’s and @badp’s comments.

In Python 3, pass the result through list() to get the same 2D list as method 2.


method 2 — list comprehension, zip_longest()

>>> [list(row) for row in six.moves.zip_longest(*list_list, fillvalue='-')]
[[1, 4, 7], [2, 5, 8], [3, 6, 9], ['-', 6.1, '-'], ['-', 6.2, '-'], ['-', 6.3, '-']]

The @inspectorG4dget alternative.


method 3 — map() of map()broken in Python 3.6

>>> map(list, map(None, *list_list))
[[1, 4, 7], [2, 5, 8], [3, 6, 9], [None, 6.1, None], [None, 6.2, None], [None, 6.3, None]]

This extraordinarily compact @SiggyF second alternative works with ragged 2D lists, unlike his first code which uses numpy to transpose and pass through ragged lists. But None has to be the fill value. (No, the None passed to the inner map() is not the fill value. It means there is no function to process each column. The columns are just passed through to the outer map() which converts them from tuples to lists.

Somewhere in Python 3, map() stopped putting up with all this abuse: the first parameter cannot be None, and ragged iterators are just truncated to the shortest. The other methods still work because this only applies to the inner map().


method 4 — map() of map() revisited

>>> list(map(list, map(lambda *args: args, *list_list)))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]   // Python 2.7
[[1, 4, 7], [2, 5, 8], [3, 6, 9], [None, 6.1, None], [None, 6.2, None], [None, 6.3, None]] // 3.6+

Alas the ragged rows do NOT become ragged columns in Python 3, they are just truncated. Boo hoo progress.


回答 5

三个选项可供选择:

1.使用Zip映射

solution1 = map(list, zip(*l))

2.列表理解

solution2 = [list(i) for i in zip(*l)]

3.对于循环追加

solution3 = []
for i in zip(*l):
    solution3.append((list(i)))

并查看结果:

print(*solution1)
print(*solution2)
print(*solution3)

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

Three options to choose from:

1. Map with Zip

solution1 = map(list, zip(*l))

2. List Comprehension

solution2 = [list(i) for i in zip(*l)]

3. For Loop Appending

solution3 = []
for i in zip(*l):
    solution3.append((list(i)))

And to view the results:

print(*solution1)
print(*solution2)
print(*solution3)

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

回答 6

也许不是最优雅的解决方案,但这是使用嵌套while循环的解决方案:

def transpose(lst):
    newlist = []
    i = 0
    while i < len(lst):
        j = 0
        colvec = []
        while j < len(lst):
            colvec.append(lst[j][i])
            j = j + 1
        newlist.append(colvec)
        i = i + 1
    return newlist

Maybe not the most elegant solution, but here’s a solution using nested while loops:

def transpose(lst):
    newlist = []
    i = 0
    while i < len(lst):
        j = 0
        colvec = []
        while j < len(lst):
            colvec.append(lst[j][i])
            j = j + 1
        newlist.append(colvec)
        i = i + 1
    return newlist

回答 7

import numpy as np
r = list(map(list, np.transpose(l)))
import numpy as np
r = list(map(list, np.transpose(l)))

回答 8

more_itertools.unzip() 易于阅读,并且还可以与生成器一起使用。

import more_itertools
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
r = more_itertools.unzip(l) # a tuple of generators.
r = list(map(list, r))      # a list of lists

或同等

import more_itertools
l = more_itertools.chunked(range(1,10), 3)
r = more_itertools.unzip(l) # a tuple of generators.
r = list(map(list, r))      # a list of lists

more_itertools.unzip() is easy to read, and it also works with generators.

import more_itertools
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
r = more_itertools.unzip(l) # a tuple of generators.
r = list(map(list, r))      # a list of lists

or equivalently

import more_itertools
l = more_itertools.chunked(range(1,10), 3)
r = more_itertools.unzip(l) # a tuple of generators.
r = list(map(list, r))      # a list of lists

回答 9

这是转置不一定为正方形的列表列表的解决方案:

maxCol = len(l[0])
for row in l:
    rowLength = len(row)
    if rowLength > maxCol:
        maxCol = rowLength
lTrans = []
for colIndex in range(maxCol):
    lTrans.append([])
    for row in l:
        if colIndex < len(row):
            lTrans[colIndex].append(row[colIndex])

Here is a solution for transposing a list of lists that is not necessarily square:

maxCol = len(l[0])
for row in l:
    rowLength = len(row)
    if rowLength > maxCol:
        maxCol = rowLength
lTrans = []
for colIndex in range(maxCol):
    lTrans.append([])
    for row in l:
        if colIndex < len(row):
            lTrans[colIndex].append(row[colIndex])

回答 10

    #Import functions from library
    from numpy import size, array
    #Transpose a 2D list
    def transpose_list_2d(list_in_mat):
        list_out_mat = []
        array_in_mat = array(list_in_mat)
        array_out_mat = array_in_mat.T
        nb_lines = size(array_out_mat, 0)
        for i_line_out in range(0, nb_lines):
            array_out_line = array_out_mat[i_line_out]
            list_out_line = list(array_out_line)
            list_out_mat.append(list_out_line)
        return list_out_mat
    #Import functions from library
    from numpy import size, array
    #Transpose a 2D list
    def transpose_list_2d(list_in_mat):
        list_out_mat = []
        array_in_mat = array(list_in_mat)
        array_out_mat = array_in_mat.T
        nb_lines = size(array_out_mat, 0)
        for i_line_out in range(0, nb_lines):
            array_out_line = array_out_mat[i_line_out]
            list_out_line = list(array_out_line)
            list_out_mat.append(list_out_line)
        return list_out_mat

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。