Python - 如何更改列表列表中的值? [英] Python - How to change values in a list of lists?

查看:60
本文介绍了Python - 如何更改列表列表中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,列表中的每个列表包含 5 个项目,如何更改列表中项目的值?我尝试了以下方法:

I have a list of lists, each list within the list contains 5 items, how do I change the values of the items in the list? I have tried the following:

    for [itemnumber, ctype, x, y, delay] in execlist:
        if itemnumber == mynumber:
            ctype = myctype
            x = myx
            y = myy
            delay = mydelay

最初我有一个元组列表,但我意识到我无法更改元组中的值,所以我切换到列表,但我仍然无法更改任何值.如果我从 for 循环中打印 ctype、x、y、delay、myctype、myx、myy 或 mydelay,似乎一切正常,但如果我之后打印 execlist,我会发现没有任何变化.

Originally I had a list of tuples but I realized I cant change values in a tuple so I switched to lists but I still cant change any of the values. If I print ctype, x, y, delay, myctype, myx, myy, or mydelay from within the for loop it appears that everything is working but if I print execlist afterwards I see that nothing has changed.

推荐答案

问题在于您正在创建列表的副本,然后修改该副本.您要做的是修改原始列表.试试这个:

The problem is that you are creating a copy of the list and then modifying the copy. What you want to do is modify the original list. Try this instead:

for i in range(len(execlist)):
    if execlist[i][0] == mynumber:
         execlist[i][1] = myctype
         execlist[i][2] = myx
         execlist[i][3] = myy
         execlist[i][4] = mydelay

这篇关于Python - 如何更改列表列表中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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