python - 转置列表列表

让我们来:

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])。剩下的只是确保结果是列表列表而不是元组列表。

https://stackoverflow.com/questions/6473679/

相关文章:

linux - 创建 zip 文件并忽略目录结构

linux - 有效地测试一个端口是否在 Linux 上打开?

python - 在 Python 中换行

python - 在 pandas DataFrame 中查找列的值最大的行

python - 如何在类中调用函数?

python - 如何理解 Python 循环的 `else` 子句?

linux - 如何在 Linux 中为每个输出行列出一个文件名?

linux - 如何包含管道 |在我的 linux 中找到 -exec 命令?

linux - 如何从我的应用程序目录中删除所有 .svn 目录

python - 如何在 Python3 中将 'binary string' 转换为普通字符串?