无法在循环中修改列表元素 [英] Can't modify list elements in a loop

查看:40
本文介绍了无法在循环中修改列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中遍历列表时,如果没有列表理解,我将无法修改元素.供参考:

While looping over a list in Python, I was unable to modify the elements without a list comprehension. For reference:

li = ["spam", "eggs"]
for i in li:
    i = "foo"

li
["spam", "eggs"]

li = ["foo" for i in li]
li 
["foo", "foo"]

那么,为什么我不能通过Python中的循环来修改元素?肯定有一些我想念的东西,但是我不知道是什么.我确定这是重复的,但是我找不到与此相关的问题,如果有链接,那就绰绰有余了.

So, why can't I modify elements through a loop in Python? There's definitely something I'm missing, but I don't know what. I'm sure this is a duplicate, but I couldn't find a question about this, and if there is a link, that would be more than enough.

推荐答案

因为 i in li 的工作方式如下:

for idx in range(len(li)):
    i = li[idx]
    i = 'foo'

因此,如果您为 i 分配任何内容,则不会影响 li [idx] .

So if you assign anything to i, it won't affect li[idx].

解决方案要么是您提出的,要么是遍历索引:

The solution is either what you have proposed, or looping through the indices:

for idx in range(len(li)):
    li[idx] = 'foo'

或使用枚举:

for idx, item in enumerate(li):
    li[idx] = 'foo'

这篇关于无法在循环中修改列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆