这是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)
最佳答案
使用你的 list 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
每次迭代会更有效率,如果您陷入循环并想要最有效的方法,那么它是一个可行的替代方案。
关于Python - 在这种情况下列表理解是有效的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31640246/