开发者

Python: How to sort a list of objects using attrgetter with case insensitivity

开发者 https://www.devze.com 2023-04-10 13:05 出处:网络
self.data = sorted(self.data, key=attrgetter(\'word\')) self.data is a list of Word objects. Word 开发者_StackOverflow中文版objects have \'word\', \'definition\', \'example\' and \'difficulty\' attr
self.data = sorted(self.data, key=attrgetter('word'))

self.data is a list of Word objects. Word 开发者_StackOverflow中文版objects have 'word', 'definition', 'example' and 'difficulty' attributes. I want to sort by the 'word' strings of each Word object, and the code above does that except it's not case insensitive. How would I go about making the sorting case insensitive?

I've tried the solutions from another question asked here, but when I tried it, it said "TypeError: 'Word' object is not subscriptable". What could I do to make it work?

Thanks.


You can write your own key function:

self.data = sorted(self.data, key = lambda w: w.word.lower())


Try something like:

self.data = sorted(self.data, key=lambda w: attrgetter('word')(w).lower())

Though, with that you would probably be much better off simply using:

self.data = sorted(self.data, key=lambda w: w.word.lower()
0

精彩评论

暂无评论...
验证码 换一张
取 消