推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
scriptB0y
V2EX  ›  Python

清空 Python list 的 100 种方法……

  •  1
     
  •   scriptB0y ·
    laixintao · Mar 23, 2018 · 6123 views
    This topic created in 3153 days ago, the information mentioned may be changed or developed.

    转载自 http://www.pythondoeswhat.com/2018/03/the-zen-of-empty-lists.html

    假如有个 list 叫做 bucket ,将其清空的方法有:

    1. bucket = []
    2. bucket.clear()
    3. del bucket[:]
    4. bucket[:]=[]
    5. bucket[:]={}
    6. bucket *=0
    7. bucket *= -3
    8. bucket *= False
    15 replies  •  2018-03-23 16:41:34 +08:00
    GlobalNPC
    GlobalNPC
    Mar 23, 2018 via Android❤️5
    1
    Python 的哲学是啥来着
    scriptB0y
    scriptB0y
    OP
    Mar 23, 2018
    2
    @infun "There should be one-- and preferably only one --obvious way to do it". >_<
    th00000
    th00000
    Mar 23, 2018
    3
    最近看到了阿里云的 redis 开发规范好像有提到这么一嘴
    使用 hscan、sscan、zscan 方式渐进式删除,同时要注意防止 bigkey 过期时间自动删除问题
    效率影响很大
    yangg
    yangg
    Mar 23, 2018
    4
    现在的标题只夸张 10 倍了?
    marcong95
    marcong95
    Mar 23, 2018
    5
    @yangg 方法 7 后面*=任意负整数都可以清空,这么看来是有 2^31 - 1 种方法,加上 lz 说的另外 7 种,那一共是有 2^31 + 6 种了,那就变成夸小了。。
    marcong95
    marcong95
    Mar 23, 2018
    6
    @yangg 负整数是 2^31 个,所以上述数字要加上 1
    msg7086
    msg7086
    Mar 23, 2018
    7
    那么喜欢把玩,为什么不去玩 Ruby 呢。
    shuizhengqi
    shuizhengqi
    Mar 23, 2018
    8
    搞不懂你要干什么,直接 list=[]不好用?
    suhaocong
    suhaocong
    Mar 23, 2018
    9
    同上 list=[]
    sleshep
    sleshep
    Mar 23, 2018
    10
    clear ()
    和
    =[]
    的副作用不一样的
    LokiSharp
    LokiSharp
    Mar 23, 2018
    11
    list=[] 会创建一个新的对象
    ipwx
    ipwx
    Mar 23, 2018 via iPhone
    12
    @shuizhengqi 复用旧 list 的缓冲空间,常数级优化。
    zbl430
    zbl430
    Mar 23, 2018
    13
    clear() python3....
    est
    est
    Mar 23, 2018❤️1
    14
    其实还好。一共就 4 种方法:

    1. 全部赋一个新的值。 = [] *= 都一样。老的没了被 GC 了
    2. .clear()
    3. del
    4. [:] = 赋值。

    我觉得 用 第二种最好。因为可以实现批量删除。但是似乎 py2 里不支持。
    Icezers
    Icezers
    Mar 23, 2018
    15
    Exception in thread "read v2ex" java.lang.ArrayIndexOutOfBoundsException: 0
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4269 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 85ms · UTC 09:32 · PVG 17:32 · LAX 01:32 · JFK 04:32
    ♥ Do have faith in what you're doing.