用列表输出而不是元组压缩 [英] Zip with list output instead of tuple
问题描述
处理两个列表中的列表的最快,最优雅的方法是什么?
What is the fastest and most elegant way of doing list of lists from two lists?
我有
In [1]: a=[1,2,3,4,5,6]
In [2]: b=[7,8,9,10,11,12]
In [3]: zip(a,b)
Out[3]: [(1, 7), (2, 8), (3, 9), (4, 10), (5, 11), (6, 12)]
我想拥有
In [3]: some_method(a,b)
Out[3]: [[1, 7], [2, 8], [3, 9], [4, 10], [5, 11], [6, 12]]
我当时正在考虑使用map而不是zip,但我不知道是否有一些标准库方法可作为第一个参数.
I was thinking about using map instead of zip, but I don't know if there is some standard library method to put as a first argument.
我可以为此定义自己的功能,并使用map,我的问题是是否已经实现了某些功能. 否也是一个答案.
I can def my own function for this, and use map, my question is if there is already implemented something. No is also an answer.
推荐答案
如果您要压缩2个以上的列表(就此而言,甚至压缩2个),一种可读的方式将是:
If you are zipping more than 2 lists (or even only 2, for that matter), a readable way would be:
[list(a) for a in zip([1,2,3], [4,5,6], [7,8,9])]
这使用列表推导,并将列表(元组)中的每个元素转换为列表.
This uses list comprehensions and converts each element in the list (tuples) into lists.
这篇关于用列表输出而不是元组压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!