gpt4 book ai didi

python - 使用生成器表达式打印每个 json 对象的多个键

转载 作者:行者123 更新时间:2023-12-01 01:31:44 25 4
gpt4 key购买 nike

我正在使用这个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]

如您所见,这给了我每个标题的长度,但我不知道实际的标题。我怎样才能打印每个 json 对象的 title 及其长度?

最佳答案

使用 lambda指定自定义排序标准:

d = sorted(payload, key=lambda x: len(x['title']))
print(d)

官方文档实际上有一个使用lambda进行排序的示例:https://docs.python.org/3/howto/sorting.html#key-functions

然后,要打印标题及其长度,您可以执行以下操作:

titles = [(p['title'], len(p['title'])) for p in sorted(payload, key=lambda x: len(x['title']))]
print(titles)
>>> [('qui est esse', 12), ('sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 74)]

关于python - 使用生成器表达式打印每个 json 对象的多个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52798607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com