列出Python中的唯一对象 [英] Make List of Unique Objects in Python
本文介绍了列出Python中的唯一对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以像这样填充" 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'}]
鉴于Python没有clone()
方法(这是我寻找的第一件事),我如何创建唯一对象而无需声明for
循环并调用append()
添加它们吗?
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?
谢谢!
推荐答案
简单的列表理解应该可以解决问题:
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'}]
这篇关于列出Python中的唯一对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文