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

如何在已有列表中创建仅含非冗余元素的列表?

解决仅保留列表中出现一次元素的问题

原代码的问题分析

  • 冗余赋值:years_of_birth = years_of_birth = [...]属于多余写法,直接写成years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]即可。
  • operator.countOf参数顺序错误:该函数第一个参数应为要统计的列表,第二个是目标元素,原代码写反了参数。
  • 核心逻辑缺失:没有将符合“出现一次”条件的元素添加到unique_ages列表,直接打印空列表无法得到有效结果。

修正后的代码方案

方法1:利用列表count()方法实现

years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
ages = []
for year in years_of_birth:
    ages.append(2022 - year)

unique_ages = []
for age in ages:
    # 统计当前age在列表中的出现次数,仅保留次数为1的元素
    if ages.count(age) == 1:
        unique_ages.append(age)

print(unique_ages)  # 输出: [30]

方法2:用collections.Counter高效统计

如果列表元素数量较多,count()方法会重复遍历列表导致效率低下,推荐用Counter一次性完成所有元素的计数:

from collections import Counter

years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
ages = [2022 - year for year in years_of_birth]  # 用列表推导式简化ages生成

age_counts = Counter(ages)
unique_ages = [age for age, count in age_counts.items() if count == 1]

print(unique_ages)  # 输出: [30]

方法3:保留元素首次出现顺序的实现

如果需要结果列表的顺序和原列表中元素首次出现的顺序一致,可以用以下方式:

years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
ages = [2022 - year for year in years_of_birth]

seen = {}
unique_ages = []
# 先统计所有元素的出现次数
for age in ages:
    seen[age] = seen.get(age, 0) + 1
# 再次遍历原列表,收集仅出现一次的元素并保证顺序
for age in ages:
    if seen[age] == 1 and age not in unique_ages:
        unique_ages.append(age)

print(unique_ages)  # 输出: [30]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:15:38