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

后端 未结 8 2162
鱼传尺愫
鱼传尺愫 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 20:50

    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:

    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]]
    

提交回复
热议问题