让我们来:
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]]
解释:
要了解发生了什么,我们需要知道两件事:
- zip 的签名:
zip(*iterables)
这意味着zip
需要任意数量的参数,每个参数都必须是可迭代的。例如。zip([1, 2], [3, 4], [5, 6])
. - Unpacked argument lists : 给定一系列参数
args
,f(*args)
将调用f
使得args
中的每个元素是f
的单独位置参数。 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/