Python:如何使用不区分大小写的属性对对象列表进行排序 [英] Python: How to sort a list of objects using attrgetter with case insensitivity

查看:26
本文介绍了Python:如何使用不区分大小写的属性对对象列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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函数:

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

这篇关于Python:如何使用不区分大小写的属性对对象列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆