python如何替换列表中的量,使用Python替换列表中的值

I have a list where I want to replace values with None where condition() returns True.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

For example, if condition checks bool(item%2) should return:

[None, 1, None, 3, None, 5, None, 7, None, 9, None]

What is the most efficient way to do this?

解决方案

Build a new list with a list comprehension:

new_items = [x if x % 2 else None for x in items]

You can modify the original list in-place if you want, but it doesn't actually save time:

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

Here are (Python 3.6.3) timings demonstrating the non-timesave:

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)

And 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值