如何从 Python 对象列表中获取唯一值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26043482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get unique values from a python list of objects
提问by Steven
I have a class:
我有一堂课:
class Car:
make
model
year
I have a list of Cars and want to get a list of unique models among my Cars.
我有一个汽车列表,想获得我的汽车中独特型号的列表。
The list is potentially tens of thousands of items. What's the best way to do this?
该列表可能包含数万个项目。做到这一点的最佳方法是什么?
Thanks.
谢谢。
采纳答案by Ffisegydd
Use a setcomprehension. Sets are unordered collections of unique elements, meaning that any duplicates will be removed.
使用set理解。集合是唯一元素的无序集合,这意味着将删除任何重复项。
cars = [...] # A list of Car objects.
models = {car.model for car in cars}
This will iterate over your list carsand add the each car.modelvalue at most once, meaning it will be a unique collection.
这将遍历您的列表cars并car.model最多添加每个值一次,这意味着它将是一个唯一的集合。
回答by Padraic Cunningham
If you want to find cars that only appear once:
如果您想查找只出现一次的汽车:
from collections import Counter
car_list = ["ford","toyota","toyota","honda"]
c = Counter(car_list)
cars = [model for model in c if c[model] == 1 ]
print cars
['honda', 'ford']
回答by henryHyman
Now it depends on what you mean by unique. If you mean Exactly the same object then this should work:
现在这取决于你所说的独特是什么意思。如果您的意思是完全相同的对象,那么这应该有效:
def check_all_objects_unique(objects: List[Any]) -> bool:
unique_objects = set(objects)
if len(unique_objects) == len(objects):
return True
elif len(unique_objects) < len(objects):
return False
If by unique you mean objects with the same attribute values then other answers on here will help you.
如果唯一是指具有相同属性值的对象,那么此处的其他答案将对您有所帮助。

