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

问题描述

在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. Thank you in advance!

推荐答案

因为for 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'

或使用enumerate:

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

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

09-05 20:38