xây dựng một danh sách mới với một sự hiểu biết danh sách:
new_items = [x if x % 2 else None for x in items]
Bạn có thể chỉnh sửa danh sách ban đầu tại chỗ nếu bạn muốn, nhưng nó không thực sự tiết kiệm thời gian:
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for index, item in enumerate(items):
if not (item % 2):
items[index] = None
Dưới đây là thời gian (Python 3.6.3) biểu thị thời gian không được phép:
In [1]: %%timeit
...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...: for index, item in enumerate(items):
...: if not (item % 2):
...: items[index] = None
...:
1.06 µs ± 33.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [2]: %%timeit
...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...: new_items = [x if x % 2 else None for x in items]
...:
891 ns ± 13.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Và Python 2.7.6 timings:
In [1]: %%timeit
...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...: for index, item in enumerate(items):
...: if not (item % 2):
...: items[index] = None
...:
1000000 loops, best of 3: 1.27 µs per loop
In [2]: %%timeit
...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...: new_items = [x if x % 2 else None for x in items]
...:
1000000 loops, best of 3: 1.14 µs per loop
sử dụng mô đun itertools, đây là mô-đun hiệu quả nhất. – LtWorf
Để biết các so sánh thay thế 'tại chỗ ', hãy xem [answer] này (http://stackoverflow.com/a/24203748/307454) – lifebalance