耗时最长(约是方法二、三的3倍),空间占用少(不生成新对象)。
耗时短,生成新列表。
耗时短,返回filter对象,取值需要通过__next()__
函数,值取完后,再调用__next__()
方法会报错。
测试代码:
import time
list1 = [1,2,3,4,5,6,7,8,9]
t1 = time.time()
# 方法一
for i in list1:
if i % 2 == 0:
list1.remove(i)
print(list1)
t2 = time.time()
print(t2 - t1)
print('-' * 30)
list1 = [1,2,3,4,5,6,7,8,9]
t1 = time.time()
# 方法二
list2 = [i for i in list1 if i % 2 == 0]
print(list1)
print(list2)
t2 = time.time()
print(t2 - t1)
print('-' * 30)
list1 = [1,2,3,4,5,6,7,8,9]
t1 = time.time()
# 方法三
list2 = filter(lambda x:x%2==0, list1)
print(list1)
print(list2.__next__())
print(list2.__next__())
print(list2.__next__())
print(list2.__next__())
t2 = time.time()
print(t2 - t1)
输出内容:
原列表: [1, 3, 5, 7, 9]
方法一耗时: 3.4332275390625e-05
------------------------------
原列表: [1, 2, 3, 4, 5, 6, 7, 8, 9]
新列表: [2, 4, 6, 8]
方法二耗时: 1.1444091796875e-05
------------------------------
原列表: [1, 2, 3, 4, 5, 6, 7, 8, 9]
新filter对象:
2
4
6
8
方法三耗时: 1.2159347534179688e-05