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

∥☆過路亽.° 提交于 2019-12-24 18:00:10

问题


self.data = sorted(self.data, key=attrgetter('word'))

self.data is a list of Word objects. Word 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.


回答1:


You can write your own key function:

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



回答2:


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()


来源:https://stackoverflow.com/questions/7656339/python-how-to-sort-a-list-of-objects-using-attrgetter-with-case-insensitivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!