Make List of Unique Objects in Python

It is possible to 'fill' an array in Python like so:

> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

I wanted to use this sample principle to quickly create a list of similar objects:

> a = [{'key': 'value'}] * 3
> a
[{'key': 'value'}, {'key': 'value'}, {'key': 'value'}]

But it appears these objects are linked with one another:

> a[0]['key'] = 'another value'
> a
[{'key': 'another value'}, {'key': 'another value'}, {'key': 'another value'}]

Given that Python does not have a clone() method (it was the first thing I looked for), how would I create unique objects without the need of declaring a for loop and calling append() to add them?

Thanks!


一个简单的列表理解应该做的诀窍:

>>> a = [{'key': 'value'} for _ in range(3)]
>>> a
[{'key': 'value'}, {'key': 'value'}, {'key': 'value'}]
>>> a[0]['key'] = 'poop'
>>> a
[{'key': 'poop'}, {'key': 'value'}, {'key': 'value'}]
链接地址: http://www.djcxy.com/p/28006.html

上一篇: Laravel 5.1:迁移现有数据库

下一篇: 在Python中制作唯一对象列表