Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

python for循环中修改变量的疑问

代码:

list = [1, 2, 3, 4, 5]
for item in list:
    item = 999
print(list)

list2 = [{'1': 1}, {'1': 1}]

for item in list2:
    item['1'] = 999
print(list2)

输出:

[1, 2, 3, 4, 5]
[{'1': 999}, {'1': 999}]

为什么第一种无法修改,而第二种修改成功了?
我怎么判断能不能修改成功?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

python中其实最多的就是引用了
看下第一个代码

list = [1, 2, 3, 4, 5]
for item in list:
    item = 999 

我把这个代码改变下就更容易看了

for i in range(len(list)):
    item = list[i]  # 到这就等价于上面代码的 for item in list,item指向list中的元素
    item = 999  # 到这一步,item重新赋值了,但list中的元素没有发生任何改变.

然后第二个代码

list2 = [{'1': 1}, {'1': 1}]

for item in list2:
    item[1]=999
    
# 改变下,看的清晰些
for i in range(len(list2)):
    item = list2[i] # 这里item指向list2[i],list2[i]是是一个列表,
    item[1] = 999 # 执行这一步就是简单的修改列表中元素的值

这个其实python中可变与不可变类型,主要还是说的python中的引用。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Qi-U Community for programmer and developer-Open, Learning and Share

755k questions

547k answers

4 comments

86.4k users

...