为了账号安全,请及时绑定邮箱和手机立即绑定

使用Python 替换列表中的值

使用Python 替换列表中的值

喵喔喔 2019-08-26 17:43:09
使用Python 替换列表中的值我有一个列表,我想用None替换值,其中condition()返回True。[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]例如,如果条件检查bool(项目%2)应该返回:[None, 1, None, 3, None, 5, None, 7, None, 9, None]最有效的方法是什么?
查看完整描述

3 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

使用列表解析构建新列表:

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

如果需要,您可以就地修改原始列表,但实际上并不节省时间:

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

以下是(Python 3.6.3)演示非时间的时间:

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)

和Python 2.7.6时序:

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 loopIn [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


查看完整回答
反对 回复 2019-08-26
?
开满天机

TA贡献1786条经验 获得超13个赞

ls = [x if (condition) else None for x in ls]


查看完整回答
反对 回复 2019-08-26
?
噜噜哒

TA贡献1784条经验 获得超7个赞

这是另一种方式:

>>> L = range (11)>>> map(lambda x: x if x%2 else None, L)[None, 1, None, 3, None, 5, None, 7, None, 9, None]


查看完整回答
反对 回复 2019-08-26
  • 3 回答
  • 0 关注
  • 2162 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信