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

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

问题描述

让我们来

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

非常感谢

推荐答案

如何

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

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

For python 3.x users can use

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

说明:

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

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

  1. zip 的签名:zip(*iterables)这表示需要任意数量的参数,每个参数必须是可迭代的.例如. zip([1, 2], [3, 4], [5, 6]).
  2. 解压参数列表:给定一系列参数argsf(*args)将调用f,以使args中的每个元素都是f的单独位置参数.
  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.

回到问题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天全站免登陆