推荐学习书目
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
jackyzy823
V2EX  ›  Python

关于修改可变迭代对象的问题,求解。

  •  
  •   jackyzy823 · Jan 26, 2013 · 4003 views
    This topic created in 4857 days ago, the information mentioned may be changed or developed.
    Python核心编程上面说:在迭代可变对象的时候修改它们并不是个好主意。

    但是我实在是想改,有什么方法。

    例如
    m=[1,2,3,4,5]

    for i in m:
    i+=1
    这样是无效的

    我现在是通过:
    for i,j in enumerate(m):
    m[i]+=1
    这样来实现更改的

    求问有没有更好的方法=w=
    3 replies    1970-01-01 08:00:00 +08:00
    qiao
        1
    qiao  
       Jan 26, 2013   ❤️ 1
    那句话的意思并不是说最好不要更改“可迭代对象的元素”,而是说不要更改这个”可迭代对象“。例如不要在迭代一个列表的时候从这个列表pop或remove元素。

    至于楼主关于修改列表中元素的问题,推荐用 m = map(lambda x: x + 1, m) 或者 m = [x + 1 for x in m] , 直接生成一个新的数组重新绑定到原来的变量上,这样可读性会好些,前提是列表不要太大,以免造成过多开销。
    PrideChung
        2
    PrideChung  
       Jan 26, 2013   ❤️ 1
    新建另一个数组n,把原数组m修改后的元素加入到n里面,然后使用n。
    BOYPT
        3
    BOYPT  
       Jan 28, 2013   ❤️ 1
    m = [i+1 for i in m]
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3099 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 08:09 · PVG 16:09 · LAX 01:09 · JFK 04:09
    ♥ Do have faith in what you're doing.