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

如何更Pythonic地实现评论列表年份提取、去重与排序功能

优化后的get_years实现方案

你原代码首先存在一个易忽略的小问题:函数定义的参数名是review,但遍历的时候用的是reviews变量,运行时会触发NameError。另外原代码返回的是字符串类型的年份,和你给出的输出示例里的整数格式不匹配。

更Pythonic的写法可以用集合生成式搭配内置sorted函数,一行就能完成需求,逻辑简洁,效率和原写法一致,可读性更高:

def get_years(reviews):
    return sorted({int(review['review_time'][-4:]) for review in reviews})

实现说明

  • 集合生成式直接遍历所有评论提取年份,自动完成去重,不需要手动初始化集合循环调用add方法
  • 内置sorted函数可以直接接收集合作为输入,不需要额外先转成列表再调用sort方法
  • 增加int()转换,返回的年份为整数类型,和你给出的输出示例格式完全匹配

效果测试

# 测试用评论列表
reviews = [
    {'rating': 5.0,
     'reviewer_name': 'Karen',
     'product_id': 'B00004RFRV',
     'review_title': 'Bialetti is the Best!',
     'review_time': '11 12, 2017',
     'images': ['https://images-na.ssl-images-amazon.com/images/I/81+XxFRGyBL._SY88.jpg'],
     'styles': {'Size:': ' 12-Cup', 'Color:': ' Silver'}},
    {'rating': 3.0,
     'reviewer_name': 'Peter DP',
     'product_id': 'B00005OTXM',
     'review_title': "Mr. Coffee DWX23 12-cup doesn't have the quality feel as my 13 year old nearly identical 12-cup Mr. Coffee",
     'review_time': '04 17, 2015',
     'images': ['https://images-na.ssl-images-amazon.com/images/I/71sFKwTW9sL._SY88.jpg'],
     'styles': {'Style Name:': ' COFFEE MAKER ONLY'}},
    {'rating': 5.0,
     'reviewer_name': 'B. Laska',
     'product_id': 'B00004RFRV',
     'review_title': 'Love my Moka pots!',
     'review_time': '07 9, 2015',
     'images': ['https://images-na.ssl-images-amazon.com/images/I/719NCqw4GML._SY88.jpg'],
     'styles': {'Size:': ' 1-Cup', 'Color:': ' Silver'}}
]

print(get_years(reviews)) # 输出 [2015, 2017]
print(type(get_years(reviews))) # 输出 <class 'list'>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:24:03