Python---lambda、enumerate的使用

源代码

#只保留得分前50的数据
results = sorted(results, key=lambda x: x['positive_score'], reverse=True)[:need]   
# 重新设置id,从0开始
for i, data in enumerate(results):
    data['id'] = i
# 将结果转换为 JSON 格式的字符串
outdata = json.dumps(results, ensure_ascii=False, indent=4)
# print(outdata)
# 将 JSON 数据写入文件
with open('yangshi-daka.json', 'w', encoding='utf-8') as json_file:
    json_file.write(outdata)

使用lambda函数作为排序的键

# 使用lambda函数作为排序的键
items = [('apple', 10), ('banana', 2), ('cherry', 5)]
# 原地修改列表
items.sort(key=lambda x: x[1])
print(items)  # 输出: [('banana', 2), ('cherry', 5), ('apple', 10)]

enumerate() 函数

  • 它用于将一个可迭代对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标。这通常用于 for 循环中,使得在迭代过程中可以同时获取到元素及其索引。
  • 能够简化很多需要索引和元素同时处理的迭代任务
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(index, fruit)
0 apple
1 banana
2 cherry

json.dumps()函数

  • 用于将 Python 对象编码成 JSON 字符串。
import json

data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

json_string = json.dumps(data, indent=4)
print(json_string)
{
    "name": "John",
    "age": 30,
    "city": "New York"
}
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只天蝎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值