现在我一直在尝试在字符串列表上执行 strip() 并且我这样做了:
i = 0
for j in alist:
alist[i] = j.strip()
i+=1
有没有更好的方法来做到这一点?
您可能不应该将其list
用作变量名,因为它是一种类型。不管:
list = map(str.strip, list)
这会将函数str.strip
应用于 中的每个元素list
,返回一个新列表,并将结果存储回list
.
你可以使用列表推导
stripped_list = [j.strip() for j in initial_list]
这里发生了一些关于性能的有趣讨论,所以让我提供一个基准:
noslice_map : 0.0814900398254
slice_map : 0.084676027298
noslice_comprehension : 0.0927240848541
slice_comprehension : 0.124806165695
iter_manual : 0.133514881134
iter_enumerate : 0.142778873444
iter_range : 0.160353899002
所以:
map(str.strip, my_list)
是最快的方式,只是比理解要快一点。
map
或者itertools.imap
如果你想应用一个函数(比如 str.split)my_list[:] = map...
,切片表示法仅引入少量开销,如果对该列表有多个引用,则可能会为您避免一些错误。
我想你的意思是
a_list = [s.strip() for s in a_list]
使用生成器表达式可能是更好的方法,如下所示:
stripped_list = (s.strip() for s in a_list)
提供惰性求值的好处,因此strip
仅在需要剥离给定元素时运行。
如果您需要对列表的引用在当前范围之外保持完整,您可能需要使用列表切片语法。:
a_list[:] = [s.strip() for s in a_list]
对于对各种方法的速度感兴趣的评论者,看起来在 CPython 中生成器到切片的方法效率最低:
>>> from timeit import timeit as t
>>> t("""a[:]=(s.strip() for s in a)""", """a=[" %d " % s for s in range(10)]""")
4.35184121131897
>>> t("""a[:]=[s.strip() for s in a]""", """a=[" %d " % s for s in range(10)]""")
2.9129951000213623
>>> t("""a=[s.strip() for s in a]""", """a=[" %d " % s for s in range(10)]""")
2.47947096824646