使用for循环(python)更改列表中的值 [英] Change values in a list using a for loop (python)

查看:1153
本文介绍了使用for循环(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屋!

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