返回信息流现有一列表如下:
l=['17\t172.16.13.1\t172.16.11.1\t0x02\t0x0\n', '\n', '\n', '\n', '\n', '\n', '\n']
我想去除列表中的回车符,我现在想到的办法如下:
new_l=[m for m in l if len(m)>5]
但是现在的问题是,如果列表非常的大
我这个过程的性能损失太大,耗时间呀。
大家有啥的好的办法吗?
这是一条镜像帖。来源:北邮人论坛 / python / #5885同步于 2015/3/27
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
列表怎样去除列表中的回车符,不损失性能。
pythonic
2015/3/27镜像同步20 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
不知道你说的 map 是不是用 filter,不过我测试了下,还是 list comprehension 快:
def escape_filter():
l = ['17\t172.16.13.1\t172.16.11.1\t0x02\t0x0\n',
'\n', '\n', '\n', '\n', '\n', '\n']
def escape_newline(value):
return value != '\n'
new_l = filter(escape_newline, l)
return new_l
def escape_lc():
l = ['17\t172.16.13.1\t172.16.11.1\t0x02\t0x0\n',
'\n', '\n', '\n', '\n', '\n', '\n']
new_l = [m for m in l if len(m) > 5]
return new_l
def escape_lc2():
l = ['17\t172.16.13.1\t172.16.11.1\t0x02\t0x0\n',
'\n', '\n', '\n', '\n', '\n', '\n']
new_l = [m for m in l if m != '\n']
return new_l
if __name__ == '__main__':
import timeit
print(timeit.timeit('escape_filter()', setup="from __main__ import escape_filter"))
print(timeit.timeit('escape_lc()', setup="from __main__ import escape_lc"))
print(timeit.timeit('escape_lc2()', setup="from __main__ import escape_lc2"))
print(escape_lc2(),escape_filter())
Results:
3.35955715179
1.92171502113
1.65116596222
【 在 reverland 的大作中提到: 】
: 过早的优化是罪恶之源
: map
: 来自「北邮人论坛手机版」