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

标签 python json

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

相关文章:

python 抓取提取 onclick 属性

python - 如何使用循环重写二维数组切片(打开cv格式)

python - 用于从两端删除非 ASCII 字符的正则表达式

json - 如何通过使用logstash将自定义格式的日志文件拆分为json?

javascript - 如何将新数字从函数传递给变量?

json - 我可以使用 FOR JSON 添加嵌套根节点吗?

python - 如何使用部分匹配查找子字符串

python - 将字符串数组(类别)从 Pandas 数据帧转换为整数数组

javascript - 如何为 JS 格式化我的 SPARQL?

javascript - 如何检查json格式的数据是否存在?