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

后端 未结 8 2027
鱼传尺愫
鱼传尺愫 2021-02-07 20:14

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 [ite         


        
相关标签:
8条回答
  • 2021-02-07 21:15

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

    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]]
    
    0 讨论(0)
  • 2021-02-07 21:15

    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:

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

    item itself 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.

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

    0 讨论(0)
提交回复
热议问题