按字母顺序对元组字符串进行排序,并按字母顺序对字符串元组进行反向排序' [英] Sorting a tuple of strings alphabetically and reverse alaphabetically'

查看:131
本文介绍了按字母顺序对元组字符串进行排序,并按字母顺序对字符串元组进行反向排序'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说您有一个元组列表(last_name,first_name),并且想要按last_name的字母顺序对它们进行排序,然后,如果两个人具有相同的名称,则按照名字的字母顺序对其进行排序.有没有办法用一行来做到这一点?

Lets say you have a list of tuples (last_name, first_name) and you want to sort them reverse alphabetically by last_name and then if two people have the same name for them to be sorted alphabetically by first name. Is there a way to do this with one line?

例如

Sorted(names, key = ?) = [('Zane', 'Albert'), ('Zane', 'Bart'), ('Python', 'Alex'), ('Python', 'Monty')]

用两行代码,我想您可以依靠排序稳定性,并首先按名字排序,然后按相反的姓氏排序.

With two lines I guess you could rely on sort stability and first sort by first name and then sort by last name reversed.

推荐答案

这是一个itertools.groupby解决方案:

from itertools import groupby
from operator import itemgetter

li = [('x', 'y'), ('s', 'e'), ('s', 'a'), ('x', 'z')]

[p for k, g in groupby(sorted(li, reverse=True), itemgetter(0)) for p in reversed(list(g))]
# [('x', 'y'), ('x', 'z'), ('s', 'a'), ('s', 'e')]
 

这篇关于按字母顺序对元组字符串进行排序,并按字母顺序对字符串元组进行反向排序'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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