2 回答
TA贡献1866条经验 获得超5个赞
您有一个嵌套的列表列表。有时有助于明显地观察这一点,注意嵌套[]语法:
json_obj = [[{'id': None}, {'id': 'abc'}, {'id': 'def'}, {'id': 'ghi'}],
[{'id': None}, {'id': 'jkl'}, {'id': 'mno'}, {'id': 'pqr'}]]
您的语法适用于单个列表:
json_obj = [{'id': None}, {'id': 'abc'}, {'id': 'def'}, {'id': 'ghi'},
{'id': None}, {'id': 'jkl'}, {'id': 'mno'}, {'id': 'pqr'}]
for d in json_obj:
print(d['id'])
对于嵌套列表,您可以使用itertools.chain.from_iterable标准库中的:
json_obj = [[{'id': None}, {'id': 'abc'}, {'id': 'def'}, {'id': 'ghi'}],
[{'id': None}, {'id': 'jkl'}, {'id': 'mno'}, {'id': 'pqr'}]]
from itertools import chain
for d in chain.from_iterable(json_obj):
print(d['id'])
或者,如果没有导入,您可以使用嵌套for循环:
for L in json_obj:
for d in L:
print(d['id'])
TA贡献1802条经验 获得超5个赞
使用嵌套列表理解。
json_obj = [[{'id': None},{'id': '5b98d01c0835f23f538cdcab'},{'id': '5b98d0440835f23f538cdcad'},{'id': '5b98d0ce0835f23f538cdcb9'}],[{'id': None},{'id': '5b98d01c0835f23f538cd'},{'id': '5b98d0440835f23f538cd'},{'id': '5b98d0ce0835f23f538cdc'}]]
print( [[j["id"] for j in i] for i in json_obj] )
或者
for i in json_obj:
for j in i:
print(j["id"])
输出:
[[None, '5b98d01c0835f23f538cdcab', '5b98d0440835f23f538cdcad', '5b98d0ce0835f23f538cdcb9'], [None, '5b98d01c0835f23f538cd', '5b98d0440835f23f538cd', '5b98d0ce0835f23f538cdc']]
添加回答
举报