You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何将列表传入函数后排序、统计元素出现次数且输出无重复

问题原因

你当前代码重复输出的核心原因是遍历了包含重复元素的完整原始列表,每一个列表元素都会触发一次打印操作,才会出现重复行。你担心转set影响统计是误解:只需要用去重后的set控制遍历的对象,统计次数依旧基于完整原始列表,就不会影响计数结果。


解决方案

方案1:用字典手动统计(效率更高,推荐)

不需要多次调用count遍历列表,仅遍历一次完成统计:

def fruit_list(fruits):
    count_dict = {}
    # 遍历一次完成次数统计
    for fruit in fruits:
        count_dict[fruit] = count_dict.get(fruit, 0) + 1
    # 按名称排序后输出
    for fruit in sorted(count_dict.keys()):
        print(fruit.title(), count_dict[fruit])

f = ["apple", "banana", "peach", "apple", "banana", "orange"]
fruit_list(f)

方案2:沿用你原有的count写法,修改遍历对象

仅把遍历对象改成排序后的去重列表即可:

def fruit_list(fruits):
    # 去重+排序,仅控制需要打印的水果名
    unique_sorted_fruits = sorted(set(fruits))
    for i in unique_sorted_fruits:
        # 统计次数依旧基于完整原始列表,不会影响计数
        fruit_occurence = fruits.count(i)
        print(i.title(), fruit_occurence)

f = ["apple", "banana", "peach", "apple", "banana", "orange"]
fruit_list(f)

方案3:使用collections.Counter(写法更简洁)

如果允许使用标准库的Counter,实现更简单:

from collections import Counter

def fruit_list(fruits):
    count = Counter(fruits)
    for fruit in sorted(count.keys()):
        print(fruit.title(), count[fruit])

f = ["apple", "banana", "peach", "apple", "banana", "orange"]
fruit_list(f)

以上所有方案的输出都完全符合你的要求:

Apple 2
Banana 2
Orange 1
Peach 1

内容的提问来源于stack exchange,提问作者PypypieYum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 09:48:00