我有以下字典串列:
menu = [{"food": "basic lasagna", "description": "basic lasagna takes tomato sauce and ground beef ."}, {"food": "carbonara pasta", "description": "there are many types of pasta in this world, but carbonara pasta is one of the best ."}, {...}, ...]
我必須用標簽突出顯示描述中的食物<food> food </food>,但我不知道如何在不使索引復雜化的情況下做到這一點。我最初的想法是:
for item in menu:
tag = item["food"]
if item["food"] in item["description"]:
i = tag.index()
tagging = "<food> " tag "</food>"
但是后來我被卡住了,因為我真的不知道如何更換該物品。有什么建議么?
uj5u.com熱心網友回復:
IIUC,您所追求的可以通過以下replace方法完成:
import json
menu = [{"food": "basic lasagna", "description": "basic lasagna takes tomato sauce and ground beef ."}, {"food": "carbonara pasta", "description": "there are many types of pasta in this world, but carbonara pasta is one of the best ."}]
for item in menu:
item["description"] = item["description"].replace(item['food'], "<food>" item['food'] "</food>")
print(json.dumps(menu, indent=4))
輸出:
[
{
"food": "basic lasagna",
"description": "<food>basic lasagna</food> takes tomato sauce and ground beef ."
},
{
"food": "carbonara pasta",
"description": "there are many types of pasta in this world, but <food>carbonara pasta</food> is one of the best ."
}
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475037.html
標籤:python-3.x 列表 字典
上一篇:通過多個嵌套鍵對資料進行分組
