题目:
编写一个程序,找出一个包含整数(也是字符串,但数字组成)和字符串的列表中最多重复的元素。
- 定义函数
most_repeated_elements()
,参数为elements_list
。 - 在函数内,计算列表中最多重复的元素,并将其返回到一个新列表中。
- 如果两个元素的出现次数相同,则将两个元素都添加到列表中(按顺序添加)并返回该列表。
示例输入
python 8 9 8 python 8 python
示例输出
['python', '8']
解释:
python
和8都重复了3次,且python
在前
代码:
from collections import Counter
def most_repeated_elements(elements_list):
# 此处写代码
count1=Counter(elements_list)
c=[]
for char,count in count1.items():
c.append((char,count))
d=sorted(c,key=lambda x:(-x[1]))
e=dict(d)
f=[char for char,v in e.items() if v==d[0][1]]
return f
# 输入一个字符串,将其拆分为列表
elements_list = input().split()
# 调用函数
print(most_repeated_elements(elements_list))