[英]From a list of string, get a list of dictionaries
我有一個字符串列表,其中包含西班牙菜譜的成分及其數量,我想獲得一份將每種成分、單位和數量分開的字典列表。
這是列表:
ingredients=[
'50',
'ccs',
'aceite',
'1',
'hoja',
'laurel',
'\n',
'1',
'cabeza',
'ajos',
'1',
'vaso',
'vino',
'1,5',
'kilos',
'conejo',
'\n',
...]
我想得到這樣的字典:
my_dic=[
{"name":"aceite" ,"qt":50 ,"unit": "ccs"},
{"name":"laurel" ,"qt":1 ,"unit": "hoja"},
{"name":"ajos" ,"qt":1 ,"unit": "cabeza"},
{"name":"vino" ,"qt":1 ,"unit": "vaso"},
{"name":"conejo" ,"qt":1,5 ,"unit": "kilos"},
...]
我一直在嘗試,但這一切都是一場災難。 有任何想法嗎?
提前致謝!!
因此,首先,您要從原始列表中刪除換行符:
ingredients = [i for i in ingredients if i is not '\n']
然后,每個成分名稱是ingredients
列表中從第三個元素開始的每隔三個元素。 同樣對於數量和單位,分別從第二個和第一個元素開始:
names = ingredients[2::3]
units = ingredients[1::3]
qts = ingredients[::3]
然后,遍歷這些列表並構造您指定的數據結構(實際上不是dict
而是dict
的list
):
my_list = []
for i in range(len(names)):
my_dict = {"name":names[i],"qt":qts[i],"unit":units[i]}
my_list.append(my_dict)
有很多方法可以壓縮以上所有內容,但我寫它是為了便於理解。
怎么樣:
ingredients = (list)(filter(lambda a: a != '\n', ingredients))
ing_organized = []
for i in range (0, len(ingredients) , 3):
curr_dict = {"name": ingredients[i+2] ,"qt": ingredients[i] ,"unit": ingredients[i+1]}
ing_organized.append(curr_dict)
我剛剛從列表中刪除了 '\n' 元素,因為它們似乎沒有意義。
這不會產生字典,但它確實為您提供了您在問題中指定的 output:
# Strip out the \n values (can possibly do this with a .strip() in the input stage)
ingredients = [value for value in ingredients if value != '\n']
labels = ['qt', 'unit', 'name']
my_dic = [dict(zip(labels, ingredients[i:i+3])) for i in range(0, len(ingredients), 3)]
my_dic
包含:
[{'qt': '50', 'unit': 'ccs', 'name': 'aceite'},
{'qt': '1', 'unit': 'hoja', 'name': 'laurel'},
{'qt': '1', 'unit': 'cabeza', 'name': 'ajos'},
{'qt': '1', 'unit': 'vaso', 'name': 'vino'},
{'qt': '1,5', 'unit': 'kilos', 'name': 'conejo'}]
您可以使用filter
清理列表以刪除\n
字符,然后將其zip()
一起收集以將您的項目收集在一起。 這使得一個快速的兩條線:
l = filter(lambda w: w != '\n', ingredients)
result = [{'name': name, 'qt':qt, 'unit': unit}
for qt, unit, name in zip(l, l, l)]
結果:
[{'name': 'aceite', 'qt': '50', 'unit': 'ccs'},
{'name': 'laurel', 'qt': '1', 'unit': 'hoja'},
{'name': 'ajos', 'qt': '1', 'unit': 'cabeza'},
{'name': 'vino', 'qt': '1', 'unit': 'vaso'},
{'name': 'conejo', 'qt': '1,5', 'unit': 'kilos'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.