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

Python字典人员数据分组排序:同年龄按姓名排序,单年龄降序

问题

现有一个人员字典(键为姓名,值为年龄),需要完成以下需求:

  1. 拆分出两类人员数据:年龄重复的人员、年龄唯一的人员
  2. 对两类数据分别排序:
    • 年龄重复的人员按姓名字母顺序排序
    • 年龄唯一的人员按年龄降序排序
  3. 最终返回这两个排序后的结果

当前编写的代码未满足需求,代码如下:

people = {'Steve' : 20 , 'David': 21 , 'Andrew' : 19 , 'Bruce': 22 ,'James' : 20 , 'Dave': 26 ,'Smith' : 19}
print('Sorted People in Alphabetical Order: ', dict(sorted(people.items())))
print('Sorted People in Numerical Order: ',dict(sorted(people.items(), key=lambda item: item[1])))

期望输出(注:原输出用集合不合理,集合是无序结构,改用列表展示有序结果):

Sorted Same Age People in Alphabetical Order: [(Andrew,19), (Smith, 19), (James,20), (Steve, 20)]
Sorted Different Ages by Age: [(Dave,26), (Bruce,22), (David,21)]

解决思路与代码

步骤分解

  • 统计年龄出现次数:先遍历字典,统计每个年龄对应的人数,以此区分重复年龄和唯一年龄。
  • 拆分人员分组:根据统计结果,将人员分别归入「年龄重复组」和「年龄唯一组」。
  • 针对性排序:对两组数据分别应用不同的排序规则。

完整代码

people = {'Steve': 20, 'David': 21, 'Andrew': 19, 'Bruce': 22, 'James': 20, 'Dave': 26, 'Smith': 19}

# 统计每个年龄的出现次数
age_counts = {}
for name, age in people.items():
    age_counts[age] = age_counts.get(age, 0) + 1

# 拆分两组数据
same_age_group = []
unique_age_group = []
for name, age in people.items():
    if age_counts[age] > 1:
        same_age_group.append((name, age))
    else:
        unique_age_group.append((name, age))

# 分别排序:重复年龄组按姓名排序,唯一年龄组按年龄降序排序
same_age_sorted = sorted(same_age_group, key=lambda x: x[0])
unique_age_sorted = sorted(unique_age_group, key=lambda x: x[1], reverse=True)

# 输出结果
print('Sorted Same Age People in Alphabetical Order: ', same_age_sorted)
print('Sorted Different Ages by Age: ', unique_age_sorted)

代码说明

  • age_counts 字典记录每个年龄的出现频次,比如19和20各出现2次,其余年龄各出现1次。
  • 拆分时通过age_counts[age] > 1判断当前人员属于哪一组。
  • 排序逻辑:
    • 重复年龄组用x[0](姓名)作为排序键,实现字母顺序排序;
    • 唯一年龄组用x[1](年龄)作为排序键,配合reverse=True实现降序排列。

运行结果

Sorted Same Age People in Alphabetical Order:  [('Andrew', 19), ('James', 20), ('Smith', 19), ('Steve', 20)]
Sorted Different Ages by Age:  [('Dave', 26), ('Bruce', 22), ('David', 21)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:35:27