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

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

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 ends of a bunch of lists by iterating over a list of these lists. I have the following code:

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

It's result, however, is:

[10, 20, 30] [10, 20, 30] [10, 20, 30] 

instead of:

[10] [20] [30] 

I can't explain why this code fails to produce the desired output, and is there some other way of doing this?

回答1:

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 ] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!