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

后端 未结 8 2226
鱼传尺愫
鱼传尺愫 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:03

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

    for i in lis:
        i = 5
    

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

    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...in construct.

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

提交回复
热议问题