从两个列表中列出列表的最快和最优雅的方法是什么?
我有
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)]
Run Code Online (Sandbox Code Playgroud)
而且我想拥有
In [3]: some_method(a,b)
Out[3]: [[1, 7], [2, 8], [3, 9], [4, 10], [5, 11], [6, 12]]
Run Code Online (Sandbox Code Playgroud)
我在考虑使用map而不是zip,但我不知道是否有一些标准库方法作为第一个参数.
我可以为我自己的功能,并使用地图,我的问题是,如果已经实现了一些东西.不是也是答案.
D K*_*D K 71
如果你要压缩2个以上的列表(或者就此而言只有2个),可读的方法是:
[list(a) for a in zip([1,2,3], [4,5,6], [7,8,9])]
Run Code Online (Sandbox Code Playgroud)
这使用列表推导并将列表中的每个元素(元组)转换为列表.
Eld*_*mir 33
你自己几乎得到了答案.不要使用map而不是zip.使用map AND zip.
您可以使用map和zip来实现优雅,实用的方法:
list(map(list, zip(a, b)))
Run Code Online (Sandbox Code Playgroud)
zip返回元组列表.map(list, [...])调用list列表中的每个元组.list(map([...])将地图对象转换为可读列表.
ksl*_*net 15
我喜欢zip功能的优雅,但在操作员模块中使用itemgetter()函数似乎要快得多.我写了一个简单的脚本来测试这个:
import time
from operator import itemgetter
list1 = list()
list2 = list()
origlist = list()
for i in range (1,5000000):
t = (i, 2*i)
origlist.append(t)
print "Using zip"
starttime = time.time()
list1, list2 = map(list, zip(*origlist))
elapsed = time.time()-starttime
print elapsed
print "Using itemgetter"
starttime = time.time()
list1 = map(itemgetter(0),origlist)
list2 = map(itemgetter(1),origlist)
elapsed = time.time()-starttime
print elapsed
Run Code Online (Sandbox Code Playgroud)
我希望zip更快,但是itemgetter方法赢了很长时间:
Using zip
6.1550450325
Using itemgetter
0.768098831177
Run Code Online (Sandbox Code Playgroud)
这个怎么样?
>>> def list_(*args): return list(args)
>>> map(list_, range(5), range(9,4,-1))
[[0, 9], [1, 8], [2, 7], [3, 6], [4, 5]]
Run Code Online (Sandbox Code Playgroud)
或者甚至更好:
>>> def zip_(*args): return map(list_, *args)
>>> zip_(range(5), range(9,4,-1))
[[0, 9], [1, 8], [2, 7], [3, 6], [4, 5]]
Run Code Online (Sandbox Code Playgroud)
Python 3 更新:
在 Python 3 中,map 返回迭代器而不是列表。这是我测试过的几个选项中最快的(使用timeit模块计时):
[list(t) for t in zip(*lists)]
Run Code Online (Sandbox Code Playgroud)
3.12 更新 目前为止最快的方法似乎是
[[*t] for t in zip(a, b)]
Run Code Online (Sandbox Code Playgroud)
我通常不喜欢使用 lambda,但是......
>>> a = [1, 2, 3, 4, 5]
>>> b = [6, 7, 8, 9, 10]
>>> c = lambda a, b: [list(c) for c in zip(a, b)]
>>> c(a, b)
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
Run Code Online (Sandbox Code Playgroud)
如果您需要额外的速度,地图会稍快一些:
>>> d = lambda a, b: map(list, zip(a, b))
>>> d(a, b)
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
Run Code Online (Sandbox Code Playgroud)
然而,map 被认为是非 Python 的,只能用于性能调整。
小智 5
我想列表理解将是非常简单的解决方案。
a=[1,2,3,4,5,6]
b=[7,8,9,10,11,12]
x = [[i, j] for i, j in zip(a,b)]
print(x)
output : [[1, 7], [2, 8], [3, 9], [4, 10], [5, 11], [6, 12]]
Run Code Online (Sandbox Code Playgroud)