转置列表列表 [英] Transpose list of lists

查看:30
本文介绍了转置列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们来看看:

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

非常感谢

推荐答案

Python 3:

# short circuits at shortest nested list if table is jagged:
list(map(list, zip(*l)))

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

Python 2:

map(list, zip(*l))

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

说明:

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

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

  1. zip 的签名:zip(*iterables) 这意味着 zip 需要任意数量的参数,每个参数都必须是可迭代的.例如.zip([1, 2], [3, 4], [5, 6]).
  2. 解压参数列表:给定一系列arguments args, f(*args) 将调用 f 使得 args 中的每个元素都是一个单独的位置参数f.
  3. itertools.zip_longest 如果嵌套列表的元素数量不同(同质),则不会丢弃任何数据,而是填充较短的嵌套列表then 拉上拉链.
  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.

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

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.

这篇关于转置列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆