我有以下資料的 JSON 檔案:
{
"P1":{
"L1":{
"crn":"1"
},
"L2":{
"crn":"100"
}
},
"P2":{
"L3":{
"crn":"xx"
},
"L4":{
"crn":"xxxx"
}
}
}
我怎樣才能[L1,L2,L3,L4]有效地獲得?我可以加載資料并回圈dict.values()。
有沒有更好、更有效的方法?
uj5u.com熱心網友回復:
您可以使用串列推導來提取房間號,然后使用itertools.chain.from_iterable將所有內容展平為一維串列:
import json
from itertools import chain
with open('input.json') as input_file:
data = json.load(input_file)
# Prints ['L1', 'L2', 'L3', 'L4']
print(list(chain.from_iterable(value.keys() for value in data.values())))
uj5u.com熱心網友回復:
在一行中使用串列理解和展平的另一種方法(假設您的 json 保存到名為 的字典中buildings):
>>> [item for sublist in buildings.values() for item in sublist]
['L1', 'L2', 'L3', 'L4']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/431208.html
