How to make a list in Python separate based on a class property in a list?

I have a list of instances from the same class, and I want to make my list different based on the property in the class. What is the most pythonic way to achieve this?

Here is a sample code:

#!/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) 

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 the lambda expression - like this:

 myList.sort(key=lambda x: x.classId) for x in myList: print x.classId $ python ./test.py 1 2 3 

Is it possible to use a similar method (lambda, map, or similar) to make the list different based on the tag property? Also, if possible, is this the most β€œpythonic” way to make a list different based on the class property in that list?

I have already tried searching for SO and Google on topics on this subject, but all the results that I found related to simple lists, which contained only a numerical value, not a user object.

+7
source share
2 answers

Assuming that the property you want to enable is immutable, you can use dict:

 d = {} for x in xs: d[x.tag] = x 

Now d will contain one x value per tag ; you can use d.values() or d.itervalues() to access xs .

NB. here the last matching item wins; to get the first victory, iterate in the opposite direction.

+6
source

You can use python dict comprehension

 {x.tag: x for x in myList}.values() 

In your example:

 >>> 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] 
+9
source

All Articles