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

2024-09-29 01:30:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我用这个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


Tags: httpscomidtitlebodypayloadpostsest
2条回答

可以分为三个阶段:

1)摘录标题

2)按长度排序

3)构建成对

这仍然很适合一行,而且实际上非常可读:

[(x, len(x)) for x in sorted((x['title'] for x in mock), key=len)]

样品运行

[('jfzq', 4), ('uqixc', 5), ('xparg', 5), ('uvuuk', 5), ('gsibnde', 7), ('pophwash', 8), ('cudisvgf', 8), ('swptewjg', 8), ('rthjtjylh', 9), ('ezvwpqhfn', 9)]

创建mock数据的代码:

>>> from random import choices, randint
>>> from string import ascii_lowercase
>>> 
>>> mock = [{k: ''.join(choices(ascii_lowercase, k=randint(4, 10))) for k in ('userId', 'id', 'title', 'body')} for _ in range(10)]

使用^{}指定自定义排序条件:

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)]

相关问题 更多 >