[英]Python - list comprehension in this case is efficient?
这是python中输入的“脏”列表
input_list = [' \n ',' data1\n ',' data2\n',' \n','data3\n'.....]
每个列表元素包含带有新行字符的空格或带有换行字符的数据
使用以下代码清理它..
cleaned_up_list = [data.strip() for data in input_list if data.strip()]
给
cleaned_up_list = ['data1','data2','data3','data4'..]
在上面的列表理解期间,python是否在内部调用了strip()
两次? 或者如果我关心效率,我是否必须使用for
循环迭代和strip()
一次?
for data in input_list
clean_data = data.strip()
if(clean_data):
cleaned_up_list.append(clean_data)
使用你的列表comp strip 被调用两次,如果你只想调用一次strip并保持理解,则使用gen exp:
input_list[:] = [x for x in (s.strip() for s in input_list) if x]
输入:
input_list = [' \n ',' data1\n ',' data2\n',' \n','data3\n']
输出:
['data1', 'data2', 'data3']
input_list[:]
将更改原始列表,这可能是你想要的,也可能不是你想要的,如果你真的想创建一个新列表,只需使用cleaned_up_list = ...
我总是发现在python 2中使用itertools.imap
并在python 3中map
而不是生成器对于较大的输入是最有效的:
from itertools import imap
input_list[:] = [x for x in imap(str.strip, input_list) if x]
一些时间采用不同的方法:
In [17]: input_list = [choice(input_list) for _ in range(1000000)]
In [19]: timeit filter(None, imap(str.strip, input_list))
10 loops, best of 3: 115 ms per loop
In [20]: timeit list(ifilter(None,imap(str.strip,input_list)))
10 loops, best of 3: 110 ms per loop
In [21]: timeit [x for x in imap(str.strip,input_list) if x]
10 loops, best of 3: 125 ms per loop
In [22]: timeit [x for x in (s.strip() for s in input_list) if x]
10 loops, best of 3: 145 ms per loop
In [23]: timeit [data.strip() for data in input_list if data.strip()]
10 loops, best of 3: 160 ms per loop
In [24]: %%timeit
....: cleaned_up_list = []
....: for data in input_list:
....: clean_data = data.strip()
....: if clean_data:
....: cleaned_up_list.append(clean_data)
....:
10 loops, best of 3: 150 ms per loop
In [25]:
In [25]: %%timeit
....: cleaned_up_list = []
....: append = cleaned_up_list.append
....: for data in input_list:
....: clean_data = data.strip()
....: if clean_data:
....: append(clean_data)
....:
10 loops, best of 3: 123 ms per loop
最快的方法实际上是itertools.ifilter
联合itertools.imap
紧随其后的是filter
与imap
。
无需重新评估函数引用list.append
每次迭代都更有效,如果您遇到循环并想要最有效的方法那么它是一个可行的替代方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.