我是靠谱客的博主 精明野狼,这篇文章主要介绍【Python CheckiO 题解】Sort Array by Element Frequency,现在分享给大家,希望可以做个参考。


CheckiO 是面向初学者和高级程序员的编码游戏,使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务,从而提高你的编码技能,本博客主要记录自己用 Python 在闯关时的做题思路和实现代码,同时也学习学习其他大神写的代码。

CheckiO 官网:https://checkio.org/

我的 CheckiO 主页:https://py.checkio.org/user/TRHX/

CheckiO 题解系列专栏:https://itrhx.blog.csdn.net/category_9536424.html

CheckiO 所有题解源代码:https://github.com/TRHX/Python-CheckiO-Exercise


题目描述

【Sort Array by Element Frequency】:对给定的可迭代对象,按照它们在列表中出现的次数进行排序,如果两个元素出现的次数相同,则按照元素在原来列表出现的先后顺序进行排序。

【链接】:https://py.checkio.org/mission/sort-array-by-element-frequency/

【输入】:可迭代的列表

【输出】:排序后的列表

【前提】:元素可以是 int 或 string 类型

【范例】

复制代码
1
2
3
frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]) == [4, 4, 4, 4, 6, 6, 2, 2] frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob']) == ['bob', 'bob', 'bob', 'carl', 'alex']

解题思路

利用 collections 模块的 Counter() 方法,统计元素的出现次数,将元素作为 key,出现次数作为 value,以字典的键值对形式存储,调用 most_common() 方法将其按照出现次数进行排序

排序过后是一个列表,列表内元素为元组的形式,遍历该列表,将元素乘以其出现的次数,依次添加到一个新的列表当中,这个新列表就是排序过后的列表

代码实现

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from collections import Counter def frequency_sort(items): items2 = [] items = Counter(items).most_common() for i in items: items2.extend([i[0]] * i[1]) return items2 if __name__ == '__main__': print("Example:") print(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4])) # These "asserts" are used for self-checking and not for an auto-testing assert list(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4])) == [4, 4, 4, 4, 6, 6, 2, 2] assert list(frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob'])) == ['bob', 'bob', 'bob', 'carl', 'alex'] assert list(frequency_sort([17, 99, 42])) == [17, 99, 42] assert list(frequency_sort([])) == [] assert list(frequency_sort([1])) == [1] print("Coding complete? Click 'Check' to earn cool rewards!")

大神解答

大神解答 NO.1

复制代码
1
2
3
def frequency_sort(items): return sorted(items, key=lambda x: (-items.count(x), items.index(x)))

大神解答 NO.2

复制代码
1
2
3
4
5
6
from collections import Counter from itertools import repeat def frequency_sort(items): return [x for y in (repeat(*x) for x in Counter(items).most_common()) for x in y]

最后

以上就是精明野狼最近收集整理的关于【Python CheckiO 题解】Sort Array by Element Frequency的全部内容,更多相关【Python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(74)

评论列表共有 0 条评论

立即
投稿
返回
顶部