Python - 如何更改列表列表中的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13752461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:32:30  来源:igfitidea点击:

Python - How to change values in a list of lists?

pythonpython-2.7

提问by Wichid Nixin

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:

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

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

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.

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

采纳答案by Jeff Silverman

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

回答by BenTrofatter

You need to assign via indexes. Let's say you've got a list of lists, where the inner lists each have 5 items like you describe. If you want to iterate through them and change the value of the second item in each inner list, you could do something like:

您需要通过索引进行分配。假设您有一个列表列表,其中每个内部列表都有您描述的 5 个项目。如果您想遍历它们并更改每个内部列表中第二项的值,您可以执行以下操作:

l = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]
for i in l:
    i[1] = "spam"

print l
(output) [[0, "spam", 2, 3, 4], [5, "spam", 7, 8, 9], [10, "spam", 12, 13, 14]]

回答by RickyA

Variable unpacking does not seem to pass the reference but copies the values. An solution would be to do it like this:

变量解包似乎没有传递引用而是复制值。一个解决方案是这样做:

foo = [[1, "gggg"], [3, "zzzz"]]

for item in foo:
    item[0] = 2
    item[1] = "ffff"

print(foo)

>>>> [[2, 'ffff'], [2, 'ffff']] 

回答by Tim Pietzcker

You could use enumerate():

你可以使用enumerate()

for index, sublist in enumerate(execlist):
   if sublist[0] == mynumber:
       execlist[index][1] = myctype
       execlist[index][2] = myx
       execlist[index][3] = myy
       execlist[index][4] = mydelay
       # break

You can remove the #if execlistonly contains at most one sublist whose first item can equal mynumber; otherwise, you'll cycle uselessly through the entire rest of the list.

您可以删除#ifexeclist只包含最多一个其第一项可以等于的子列表mynumber;否则,您将无用地循环遍历列表的其余部分。

And if the itemnumbersare in fact unique, you might be better off with a dictionary or at least an OrderedDict, depending on what else you intend to do with your data.

如果itemnumbers实际上是唯一的,则最好使用字典或至少使用OrderedDict,这取决于您打算对数据做什么。

回答by ApproachingDarknessFish

Don't assign local variables in lists. In the loop

不要在列表中分配局部变量。在循环

for i in lis:
    i = 5

Just sets the variable ito 5 and leaves the actual contents of the list unchanged. Instead, you have to assign it directly:

只需将变量设置i为 5 并保持列表的实际内容不变。相反,您必须直接分配它:

for i in range(len(lis)):
     lis[i] = 5

The same applied for lists of lists, although in this case the local variable doesn't have to be assigned so you can use the for...inconstruct.

这同样适用于列表列表,尽管在这种情况下不必分配局部变量,因此您可以使用该for...in构造。

for i in listoflists:
     for i2 in range(len(i)):
          i[i2] = 5 #sets all items in all lists to 5

回答by martineau

Changing the variables assigned in the fordoes not change the list. Here's a fairly readable way to do what you want:

更改在 中分配的变量for不会更改列表。这是一个相当易读的方法来做你想做的事:

execlist = [
    #itemnumber, ctype, x, y, delay
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15],
]

mynumber, myctype, myx, myy, mydelay = 6, 100, 101, 102, 104

for i, sublist in enumerate(execlist):
   if sublist[0] == mynumber:
        execlist[i] = [mynumber, myctype, myx, myy, mydelay]

print execlist

Output:

输出:

[[1, 2, 3, 4, 5], [6, 100, 101, 102, 104], [11, 12, 13, 14, 15]]

回答by dbrobins

The iterator variables are copies of the original (Python does not have a concept of a reference as such, although structures such as lists are referred to by reference). You need to do something like:

迭代器变量是原始变量的副本(Python 本身没有引用的概念,尽管列表等结构是通过引用引用的)。您需要执行以下操作:

for item in execlist:
    if item[0] == mynumber:
        item[1] = ctype
        item[2] = myx
        item[3] = myy
        item[4] = mydelay

itemitself is a copy too, but it is a copy of a reference to the original nested list, so when you refer to its elements the original list is updated.

item本身也是一个副本,但它是对原始嵌套列表的引用的副本,因此当您引用其元素时,原始列表会更新。

This isn't as convenient since you don't have the names; perhaps a dictionary or class would be a more convenient structure.

这不太方便,因为您没有名字;也许字典或类会是一个更方便的结构。

回答by Erik Ware

Here is an example I used recently, it was a real mind bender but hopefully it can help out some one!

这是我最近使用的一个例子,它是一个真正的头脑弯曲,但希望它可以帮助一些人!

pivot_peaks is a list of pandas data frames some of them are duplicates.

pivot_peaks 是熊猫数据框的列表,其中一些是重复的。

# Create a new list with only a single entry for each item
new_list = []

for obj_index, obj in enumerate(pivot_peaks):
    add_new_frame = False

    if len(new_list) == 0:
        new_list.append(obj)
    else:
        for item in new_list:
            if item.equals(obj):
                add_new_frame = False
                break
            else:
                add_new_frame = True

        if add_new_frame == True:
            new_list.append(obj)