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.
v3gard
source share