我用这个API https://jsonplaceholder.typicode.com/posts列出所有这样的帖子
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
我的密码
session = requests.Session()
payload = session.request("GET", "https://jsonplaceholder.typicode.com/posts", timeout = 30).json()
print(payload)
现在我想按id
对所有对象进行排序
d = sorted(payload, key=operator.itemgetter("id"))
print(d)
如果我想按标题的长度排序
我不知道如何使用operator
来提供len(title)
作为键有可能吗
使用带有for
循环的生成器表达式而不是key
d = sorted(len(value["title"]) for value in payload)
print(d)
输出
[12, 12, 14, 14, 15, 18, 20, 20, 20, 20, 23, 24, 24, 24, 24, 24, 24, 25, 25, 26, 26, 26, 27, 27, 29, 29, 29, 30, 30, 30, 31, 32, 32, 32, 32, 33, 33, 33, 33, 34, 34, 34, 35, 36, 37, 37, 37, 37, 38, 38, 39, 39, 39, 40, 40, 41, 41, 41, 41, 42, 42, 42, 42, 43, 43, 43, 43, 44, 44, 44, 45, 46, 47, 47, 47, 49, 50, 50, 51, 51, 53, 53, 53, 53, 54, 55, 55, 55, 57, 59, 60, 60, 67, 68, 72, 74, 76, 76, 78, 79]
如您所见,这给了我每个title
的长度,但我不知道实际的标题。如何在每个json对象的长度旁边打印title
可以分为三个阶段:
1)摘录标题
2)按长度排序
3)构建成对
这仍然很适合一行,而且实际上非常可读:
样品运行
创建
mock
数据的代码:使用^{} 指定自定义排序条件:
官方文档实际上有一个用
lambda
排序的例子:https://docs.python.org/3/howto/sorting.html#key-functions然后,要打印标题及其长度,可以执行以下操作:
相关问题 更多 >
编程相关推荐