Python:如何使用不区分大小写的 attrgetter 对对象列表进行排序
self.data = sorted(self.data, key=attrgetter('word'))
self.data 是 Word 对象的列表。 Word 对象具有“单词”、“定义”、“示例”和“难度”属性。我想按每个 Word 对象的“单词”字符串进行排序,上面的代码可以做到这一点,只是它不区分大小写。我将如何使排序不区分大小写?
我已经尝试了此处提出的另一个问题的解决方案,但是当我尝试它时,它说“TypeError:'Word'对象不可下标”。我能做些什么来让它发挥作用?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以编写自己的
key
函数:You can write your own
key
function:尝试类似的方法:
不过,这样你可能会更好地简单地使用:
Try something like:
Though, with that you would probably be much better off simply using: