相关疑难解决方法(0)

为什么我不能使用 for 循环 (python) 更改或重新分配列表中变量的值?

如果我有一个数字列表,并且我想使用 for 循环来增加它们,为什么这不起作用:

>>> list=[1,2,3,4,5]
>>> for num in list: 
...  num=num+1
... 
>>> list
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

我期望得到 [2,3,4,5,6]。

我知道我可以通过这样做来解决这个问题

>>> newlist=[] 
>>> for num in list: 
...  newlist.append(num+1)
... 
>>> newlist
[2, 3, 4, 5, 6]
>>> 
Run Code Online (Sandbox Code Playgroud)

但一定有更简单的方法。

python

2
推荐指数
2
解决办法
734
查看次数

标签 统计

python ×1