使用for循环(python)更改列表中的值 [英] Change values in a list using a for loop (python)
问题描述
我目前有一些代码如下:
I currently have some code that reads like this:
letters = {
10 : "A",
11 : "B",
12 : "C",
13 : "D",
14 : "E",
15 : "F"
}
vallist = [rd1, rd2, gd1, gd2, bd1, bd2]
for i in vallist:
if i >= 10:
i = letters[i]
我想发生的是for循环,以遍历vallist
并将大于10的任何值替换为其对应的字母.但是,我当前的代码只是更改了i
而不是列表中的原始值.例如,如果rd1
设置为15,则代码运行并且i
设置为"F"
,但是rd1
不会更改为"F"
,而是停留在15.我该如何解决这个吗?
What I want to happen is the for loop to iterate through vallist
and replace any value that is greater than 10 with its corresponding letter. However, my current code just changes i
and not the original value in the list. For example, if rd1
is set to 15, the code runs through and i
is set to "F"
, but rd1
does not change to "F"
, and instead just stays as 15. How can I fix this?
推荐答案
对于for
循环的每次迭代,变量i
仅分配有vallist
中项目值的副本,因此需要进行更改对i
所做的操作不会反映在i
中.
For each iteration of the for
loop the variable i
is assigned with just a copy of the value of an item in vallist
, so changes made to i
won't be reflected in i
.
您应该通过索引更新i
的各项,可以使用enumerate
函数生成该索引:
You should update the items of i
via index, which you can generate with the enumerate
function:
for index, value in enumerate(vallist):
if value >= 10:
vallist[index] = letters[value]
这篇关于使用for循环(python)更改列表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!