简体   繁体   中英

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 simple list comprehension should do the trick:

>>> 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'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM