Having trouble making a list of lists of a designated size [duplicate]

☆樱花仙子☆ 提交于 2019-12-17 02:51:48

问题


I am trying to make a list of lists of about 5000 lists and it keeps messing up.
right now I just do this:

array = [[]]*5000
for line in f2:
    a = line.split()
    grid = int(a[0])
    array[grid].append(a[1])

print Counter(array[0]).most_common(10)

the problem is when I make the counter it does it as if the whole array of lists was actually just one list. Is there something obvious that I am doing wrong? Thanks


回答1:


Using [[]]*5000, you are creating 5000 reference to the same list in your outer list. So, if you modify any list, it will modify all of them.

You can get different lists like this:

a = [[] for _ in xrange(5000)]


来源:https://stackoverflow.com/questions/17411892/having-trouble-making-a-list-of-lists-of-a-designated-size

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