我想從像這樣的 json 檔案中獲取一個 url:
[
{
"Index": 6,
"Title": "A Simple Monitoring",
"URL": "http://www.vn-meido.com/k1/index.php?PHPSESSID=4e30s552gamla57pl6hdhe2cn4&topic=1497.msg20688"
},
{
"Index": 7,
"Title": "A Simple Survey",
"URL": "http://www.vn-meido.com/k1/index.php?PHPSESSID=4e30s552gamla57pl6hdhe2cn4&topic=1283.0"
},
]
有沒有使用“索引”號獲取網址的方法?
uj5u.com熱心網友回復:
def get_url_by_index(json_list, i):
for dictionary in json_list:
if dictionary['Index'] == i:
return dictionary['URL']
使用您的 json 物件和指定的索引呼叫此函式,它應該可以解決您的問題。它只是遍歷串列并檢查每個字典的索引值。
uj5u.com熱心網友回復:
您可以通過在 python 中創建一個字典來實作這一點,這需要在索引時遍歷串列。
dat = [
{
"Index": 6,
"Title": "A Simple Monitoring",
"URL": "http://www.vn-meido.com/k1/index.php?PHPSESSID=4e30s552gamla57pl6hdhe2cn4&topic=1497.msg20688"
},
{
"Index": 7,
"Title": "A Simple Survey",
"URL": "http://www.vn-meido.com/k1/index.php?PHPSESSID=4e30s552gamla57pl6hdhe2cn4&topic=1283.0"
},
]
dat_dict = {}
for item in dat:
dat_dict[item['Index']] = item['URL']
print(dat_dict[6])
print(dat_dict[7])
創建字典后,從中訪問元素將比每次回圈遍歷整個串列要快得多。
uj5u.com熱心網友回復:
啊,所以這是一個字典串列,似乎您可以使用串列推導來有效地“過濾”串列。
例如,您想要索引 6、7 和 11 的 url
wanted_url_ids = [6, 7, 11]
[url_dict for url_dict in json_file if url_dict[index] in wanted_url_ids]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/421245.html
標籤:
