当用于列表时,什么是operater *真的意味着什么?

时间:2015-06-18 06:49:46

标签: python python-2.7 python-3.x

我试图实现像C structure之类的东西,所以我预定了一个清单:

__list = [0] * 1001
一切顺利。

但是当列表变得复杂时(样本):

__list = [{"name": '', "score": 0}] * 3

for item in __list:
    name, score = input("input name and score split with blank:\n").split()    # raw_input for python2
    item['name'] = name
    item['score'] = int(score)
print(__list)

我输入了这个:

Lily 23
Paul 12
James 28

出:

[{"name": "James", "score": 28}, {"name": "James", "score": 28}, {"name": "James", "score": 28}]

为什么呢?

1 个答案:

答案 0 :(得分:3)

__list = [{"name": '', "score": 0}] * 3

这将为字典创建一个包含三个引用的列表。修改它们中的任何一个都会修改它们,因为它们都引用相同的数据。

如果您希望列表包含对不同词典的引用,您可以执行"深层复制"通过使用列表推导来引用词典,例如,

__list = [{"name": '', "score": 0} for i in xrange(3)]