Creating and working with list of lists of lists: in Python [duplicate]

时光毁灭记忆、已成空白 提交于 2019-12-11 10:05:11

问题


I'm new with Python and for some needs I am trying to figure out how to work with list of lists of lists.

Here's what am I doing:

segment_coef = [[list()]*4]*17 
print segment_coef
segment_coef[0][0].append(1)
segment_coef[1][0].append(2)
segment_coef[2][0].append(3)
print segment_coef

After first print I have :

[ [ [],[],[],[] ] , ... 14 more time ... , [ [],[],[],[] ] ]


After these three append commands I'd like to have smth like:

[ [ [1],[],[],[] ] , [ [2],[],[],[] ], [ [3],[],[],[] ] ]

But I've got:

[ [ [1,2,3],[1,2,3],[1,2,3],[1,2,3] ] , [ [1,2,3],[1,2,3],[1,2,3],[1,2,3] ], ... up to the end ]

What am I doing wrong?


回答1:


There are a couple of ways to create a list of 17 lists of 4 sublists each

the shortest would be

[[list() for i in range(4)] for j in range(17)] 

If you do this, your appends will work as you want them to

If you're familiar with languages like C or Java that don't have list comprehensions, this way might look more familiar to you:

l = []
for j in range (17):
  k = []
  for i in range (4):
    k.append(list())
  l.append (k)

This is also acceptable, but for many python heads, the list comprehension is preferable. The list comp should be performance-wise at least as good as the comprehension.




回答2:


Python is using the same list 4 times, then it's using the same list of 4 lists 17 times!

The issue here is that python lists are both mutable and you are using (references to) the same list several times over. So when you modify the list, all of the references to that list show the difference.

Depending on how/where you get your data from, depends on the best way to fix it, but something like:

lols = []
for i in range(17):
    lols.append([1,2,3,4])
# lols is not a list of 17 lists, each list contains the same data but they are different lists
lols[0][0] = 99
# Now only the first element from the first list is updated.

To be clear, the issue comes from doing [list() * 4], which construsts the list ones (using list) and then repeats it 4 times. If you did [list(), list()m list(), list()] you would get 4 different (but all empty) lists, or, more pythonically, [list() for _ in range(4)] or just [[] for _ in range(4)]



来源:https://stackoverflow.com/questions/27475539/creating-and-working-with-list-of-lists-of-lists-in-python

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