Python:如何使用不区分大小写的attrgetter对对象列表进行排序 [英] Python: How to sort a list of objects using attrgetter with case insensitivity
问题描述
self.data = sorted(self.data, key=attrgetter('word'))
self.data是Word对象的列表.单词对象具有单词",定义",示例"和难度"属性.我想按每个Word对象的'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?
我已经尝试过在此处问到的另一个问题的解决方案,但是当我尝试时,它说"TypeError:'Word'对象不可下标".我该怎么做才能使其正常工作?
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?
谢谢.
推荐答案
您可以编写自己的key
函数:
You can write your own key
function:
self.data = sorted(self.data, key = lambda w: w.word.lower())
这篇关于Python:如何使用不区分大小写的attrgetter对对象列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!