按数字和字母顺序对两个元素元组的列表进行排序 [英] Sorting a list of two element tuples numerically and alphabetically

查看:75
本文介绍了按数字和字母顺序对两个元素元组的列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务,我必须从一个字符串创建一个元组列表.我通过用 .split() 分割字符串来做到这一点.然后我遍历列表并将项目和每个项目的重复次数添加到字典中,如下所示:

I have an assignment in which I must create a list of tuples from a string. I do this by splitting the string with .split(). I then iterate over the list and add the items and the number of repetitions of each item into a dict, like so:

 for word in s:         
    if word in count_dict:
        count_dict[word] += 1
    else:
        count_dict[word] = 1

在此之后,我使用以下方法创建了一个元组列表:

After this I create a list of tuples using:

pairs = count_dict.items()

关注:

count_list = []
for pair in pairs:
    count_list.append(pair)

count_list.sort(key=lambda x: x[1], reverse=True)

我按照每个元组中最大 x[1] 元素的顺序排序并反转列表,以便我将重复次数最多的项目放在前面.我的实际任务是让重复次数最多的元素先出现,重复次数相同的元素按字母顺序出现在最大的元素后面.

I sort in the order of largest x[1] element in each tuple and reverse the list so that I have the items with he most repetitions up front. My actual assignment is to have the elements with the highest repetitions appear first, and to have elements with the same number of repetitions to appear in alphabetical order behind the largest elements.

推荐答案

另一种反转数字排序的方法是在键函数中使数字为负

Another way to reverse a numeric sort is to make the numbers negative in the key function

现在与第二个排序顺序组合成一个元组

Now combining with the second sort order into a tuple

count_list.sort(key=lambda x: (-x[1], x[0]))

有必要去掉reverse=True,否则字母顺序会颠倒.

It's necessary to get rid of the reverse=True, as otherwise the alphabetical sort will be reversed.

这篇关于按数字和字母顺序对两个元素元组的列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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