源代码
results = sorted(results, key=lambda x: x['positive_score'], reverse=True)[:need]
for i, data in enumerate(results):
data['id'] = i
outdata = json.dumps(results, ensure_ascii=False, indent=4)
with open('yangshi-daka.json', 'w', encoding='utf-8') as json_file:
json_file.write(outdata)
使用lambda函数作为排序的键
items = [('apple', 10), ('banana', 2), ('cherry', 5)]
items.sort(key=lambda x: x[1])
print(items)
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"
}