如何筛选income=2的行并按age降序排列?能否不依赖额外库实现?
筛选income=2的行并按age降序排列(无额外库实现)
先明确下,假设你的数据是Python原生的列表嵌套字典结构(符合常见的表格类数据存储方式),示例如下:
data = [ {"name": "Alice", "age": 25, "income": 1}, {"name": "Bob", "age": 30, "income": 2}, {"name": "Charlie", "age": 22, "income": 2}, {"name": "David", "age": 35, "income": 3}, {"name": "Eve", "age": 28, "income": 2} ]
实现步骤
完全可以不用任何第三方库,用Python内置功能就能搞定:
- 筛选income=2的行
用列表推导式快速过滤:
filtered_rows = [row for row in data if row["income"] == 2]
这行代码会遍历所有数据行,只保留income字段等于2的条目。
- 按age降序排序
用内置的sorted()函数,通过key指定排序依据为age字段,reverse=True开启降序:
sorted_result = sorted(filtered_rows, key=lambda x: x["age"], reverse=True)
也可以把两步合并成一行代码:
final_result = sorted([row for row in data if row["income"] == 2], key=lambda x: x["age"], reverse=True)
最终结果
执行后得到的结果如下:
[ {"name": "Bob", "age": 30, "income": 2}, {"name": "Eve", "age": 28, "income": 2}, {"name": "Charlie", "age": 22, "income": 2} ]
总结:完全不需要额外库,Python原生的列表推导式和sorted()函数就能完成需求。
内容的提问来源于stack exchange,提问作者papi
相关产品推荐
相关产品推荐

