Python: Appending items to lists by iterating through list of lists

前端 未结 1 647
别跟我提以往
别跟我提以往 2021-01-20 08:18

I\'m a Python newbie crossing over from C. I\'m basically trying implement logic equivalent to an array of array pointers in C.

I want to append one item to the end

相关标签:
1条回答
  • 2021-01-20 09:17

    You only create one list

    list1 = list2 = list3 = list()
    

    this line creates an empty list, assigns its reference to list3, assigns reference to list3 to list2 and to list1, as a result these refer to the same object. So when you add your values, you add them to all of your "lists".

    This will work just fine

    data = [10, 20, 30]
    lists = [[], [], []]
    
    for i in range(len(data)):
        lists[i].append(data[i])
    
    for lst in lists:
        print lst
    

    But the simplest way would be to do just

    data = [10, 20, 30]
    lists = [ [x] for x in data ]
    
    0 讨论(0)
提交回复
热议问题