Python - 将同一函数应用于列表元素的最快方法是什么

时间:2017-05-13 08:45:27

标签: python list

我有这个清单

l = ['2017-05-13 00:00:00', '2017-05-12 00:00:00', '2017-05-11 00:00:00']

我希望为每个元素删除00:00:00部分。 elm = elm.split(" ")[0]

有没有比

更快的方法
for elm in l:
    elm = elm.split(" ")[0]

3 个答案:

答案 0 :(得分:1)

您应该有一个空列表,以便将拆分的部分附加到它,但可能您省略了追加部分。

new = []
for elm in l:
    elm = elm.split(" ")[0]
    new.append(elm)

但更优化的方法是使用列表理解:

In [16]: [i.split()[0] for i in l]
Out[16]: ['2017-05-13', '2017-05-12', '2017-05-11']

答案 1 :(得分:0)

最快的方法是使用list comprehension,以下是一些情况:

案例0:

l = ['2017-05-13 00:00:00', '2017-05-12 00:00:00', '2017-05-11 00:00:00']
start0 = time.time()
output = []
for data in l:
    data = data.split(" ")[0]
    output.append(data)
print(output)
print(time.time()-start0)
['2017-05-13', '2017-05-12', '2017-05-11']
5.602836608886719e-05

案例1:lambdamap()

l = ['2017-05-13 00:00:00', '2017-05-12 00:00:00', '2017-05-11 00:00:00']
start1 = time.time()
print(list(map(lambda x:x.split(" ")[0],l)))
print(time.time()-start1)
['2017-05-13', '2017-05-12', '2017-05-11']
3.504753112792969e-05

案例2:list comprehension

l = ['2017-05-13 00:00:00', '2017-05-12 00:00:00', '2017-05-11 00:00:00']
start2 = time.time()
print([i.split()[0] for i in l])
print(time.time()-start2)
['2017-05-13', '2017-05-12', '2017-05-11']
0.00010156631469726562

答案 2 :(得分:0)

当您的数据时间字符串具有固定大小时,您可以直接对字符串进行切片:

>>> l = ['2017-05-13 00:00:00', '2017-05-12 00:00:00', '2017-05-11 00:00:00']
>>> [i[:10] for i in l]
['2017-05-13', '2017-05-12', '2017-05-11']