简体   繁体   English

在Python中创建唯一对象列表

[英]Make List of Unique Objects in Python

It is possible to 'fill' an array in Python like so: 可以在Python中“填充”一个数组,如下所示:

> [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? 鉴于Python没有clone()方法(这是我首先想到的), 如何创建唯一对象而不需要声明for循环并调用append()来添加它们?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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