水果排序

msg = "香焦 梨子 火龙果 苹果 苹果 香焦 哈密瓜 苹果"
# 用空格切,得到列表
msg_list = msg.split(" ")
print(msg_list)
# 列表的统计
msg_dict = {}
for fruit in msg_list:
msg_dict[fruit] = msg_dict.get(fruit, 0) + 1
print(msg_dict)
# 排序
print(msg_dict.items())
# dict_items([('香焦', 2), ('梨子', 1), ('火龙果', 1), ('苹果', 3), ('哈密瓜', 1)])
ls = list(msg_dict.items())
ls.sort(key=lambda x: x[1], reverse=True)
print(ls)
# 创建一个文件对象
f = open("PY202.txt", "w", encoding="utf8")
content = ""
for fruit_tuple in ls:
content += "{}:{}\n".format(fruit_tuple[0], fruit_tuple[1])
f.write(content)
f.close()
C:\Users\python_hui\Anaconda3\python.exe G:/test/a/111/11.py
[‘香焦’, ‘梨子’, ‘火龙果’, ‘苹果’, ‘苹果’, ‘香焦’, ‘哈密瓜’, ‘苹果’]
{‘香焦’: 2, ‘梨子’: 1, ‘火龙果’: 1, ‘苹果’: 3, ‘哈密瓜’: 1}
dict_items([(‘香焦’, 2), (‘梨子’, 1), (‘火龙果’, 1), (‘苹果’, 3), (‘哈密瓜’, 1)])
[(‘苹果’, 3), (‘香焦’, 2), (‘梨子’, 1), (‘火龙果’, 1), (‘哈密瓜’, 1)]
Process finished with exit code 0
卖火柴的小女孩

1

本博客介绍了一种使用Python进行水果名称统计及排序的方法。通过将输入的水果名称字符串转换为列表,然后统计每种水果出现的次数,并最终按数量降序排列。此过程涉及字符串操作、字典和列表的使用,以及文件读写操作。
4258

被折叠的 条评论
为什么被折叠?



