python - 转置列表列表

标签 python list transpose

让我们来:

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

解释:

要了解发生了什么,我们需要知道两件事:

  1. zip 的签名: zip(*iterables) 这意味着 zip 需要任意数量的参数,每个参数都必须是可迭代的。例如。 zip([1, 2], [3, 4], [5, 6]).
  2. Unpacked argument lists : 给定一系列参数 argsf(*args) 将调用 f 使得 args 中的每个元素是 f 的单独位置参数。
  3. itertools.zip_longest 如果嵌套列表的元素数量不相同(同质),则不会丢弃任何数据,而是填充较短的嵌套列表然后 拉上 zipper 。

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

关于python - 转置列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6473679/

相关文章:

python - 在python中将数据追加到文件末尾

python - 具有嵌套列表的多个值的字典

mysql - 如何在EXCEL或SQL中转置动态矩阵数据集

sql - 将一些列转置为行

Python 给出冗长的输出,表明模块正在被销毁

python - pygame 跳过更新屏幕

python - 为什么 SymPy 不理解对数积

python-3.x - Hackerrank 列出问题 ~ 标准测试用例有效但其他无效

java - 无法添加到数组列表

php - 转置查询结果集