开发者

list sorting case insensitive using operator.attrgetter

hi i have list of dictionaries .. and i want to sort it case insensitive

members = Person.objects.filter(person=person_id)
mem开发者_开发技巧bers_list = list(members)

members_list.sort( key = operator.attrgetter( sort_by ), reverse = False )

here sort_by have attribute name by whom i want to sort. Now how can i sort with case insensitive ??

Please help..


members_list.sort( key = lambda member: getattr(member,sort_by).lower(), reverse = False )


If sort_by is a variable containing a string with the name of the attribute you want to use for sorting and you want to use operator.attrgetter(), you could use this which converts the value of the attribute it fetches to all lowercase characters for comparisons during the sort:

members_list.sort( key = lambda mbr: operator.attrgetter( sort_by )( mbr ).lower(),
                   reverse = False )

Although something like the following is easier to read as well as more efficient:

get_key = operator.attrgetter( sort_by )
members_list.sort( key = lambda mbr: get_key( mbr ).lower(), reverse = False )


It seems this question is about django. You might want to think about returning a sorted queryset instead. This means you can leave the sorting too the database and not bother with it your self. See this site: django

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜