gpt4 book ai didi

python 3.x : How do I sort a list of tuples that has the same second element (count) by string value?

转载 作者:行者123 更新时间:2023-11-28 22:33:53 25 4
gpt4 key购买 nike

比如

['John','John','Mike','Mike','Kate','Kate']

应该返回:

[('John', 2), ('Kate', 2), ('Mike', 2)]

我怎样才能编写代码以确保有顺序而不是这三对只是随机排列?

我需要按照从大到小的计数对元组列表进行排序,除非有联系,然后我需要按字母顺序对时间进行排序。

最佳答案

这个有效:

>>> names = ['John','John','Mike','Mike','Kate','Kate']
>>> sorted(Counter(names).items(), key=lambda item: (-item[1], item[0]))
[('John', 2), ('Kate', 2), ('Mike', 2)]

计数器的项目将为您提供 (name, count) 的元组。通常您会使用 Counter.most_common 来按计数顺序获取项目,但据我所知,它仅按计数排序并忽略排序中的任何键(名称)信息。

既然我们无论如何都要重新排序,我们不妨对项目使用sorted。由于元组按字典顺序排序,而您希望主要按计数排序,因此 key 函数应返回格式为 (count, name) 的元组。但是,由于您希望它按计数减少,但按名称​​增加,我们唯一能做的就是返回格式为 (-count , 姓名)。这样,较大的计数将导致较低的值,因此它将在 具有较低计数的值之前排序。

关于 python 3.x : How do I sort a list of tuples that has the same second element (count) by string value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39482968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com