如何根据列表中类的属性使Python中的列表与众不同? [英] How to make a list in Python distinct based on a property of the class in the list?
问题描述
我有一个来自同一类的实例的列表,并且我想根据该类中的属性来使列表与众不同.实现这一目标的最有效方法是什么?
I have a list of instances from the same class, and I want to make my list distinct based on a property in the class. What is the most pythonic way to achieve this?
以下是一些示例代码:
#!/usr/bin/python
#-*- coding:utf-8 -*-
class MyClass(object):
def __init__(self, classId, tag):
self.classId = classId
self.tag = tag
myList = []
myInstance1 = MyClass(1, "ABC")
myInstance2 = MyClass(2, "DEF")
myInstance3 = MyClass(3, "DEF")
myList.append(myInstance1)
myList.append(myInstance3) # note that the order is changed deliberately
myList.append(myInstance2)
如果我现在想基于MyClass中的属性之一对列表进行排序,我通常只需按键对其进行排序,并使用lambda表达式设置键-像这样:
If I want to sort my list now based on one of the properties in MyClass, I usually just sort it by key, and set the key using a lambda expression - like this:
myList.sort(key=lambda x: x.classId)
for x in myList:
print x.classId
$ python ./test.py
1
2
3
是否可以使用类似的方法(lambda,map或类似方法)基于"tag"属性使列表与众不同?另外,如果可能的话,是否是基于列表中类的属性使列表与众不同的最"pythonic"方法?
Is it possible to use a similar method (lambda, map or similar) to make the list distinct based on the "tag" property? Also, if this is possible, is it the most "pythonic" way to make a list distinct based on a property of a class in that list?
我已经尝试在SO和Google上搜索有关此问题的主题,但是我发现的所有结果都处理了仅包含数字值而不包含自定义对象的简单列表.
I have already tried searching both SO and Google for topics on this matter, but all the results I found dealt with simple lists that only contained a numeric value and not a custom object..
推荐答案
您可以使用 python dict comprehension
{x.tag: x for x in myList}.values()
以您的示例为例:
>>> class MyClass(object):
... def __init__(self, classId, tag):
... self.classId = classId
... self.tag = tag
...
>>> myList = [MyClass(1, "ABC"), MyClass(2, "DEF"), MyClass(3, "DEF")]
>>> uniqList = {x.tag: x for x in myList}.values()
>>> print [x.classId for x in uniqList]
[1, 3]
这篇关于如何根据列表中类的属性使Python中的列表与众不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!