我有以下方式的列表和字典:
lista = [
['Pasta', 'is', 'bad'],
['Pasta', 'is', 'good', 'and','is','expensive']
]
dica = {
'Pasta': 0,
'is': 0,
'bad': 0,
'good': 0,
'and': 0,
'expensive': 0
}
我想获取列表中的每个子列表并对其应用字典,创建一个字典列表-每个列表一个-其中每个键的值是该键在子列表中出现的次数。 / p>
fin_dict = {
{
'Pasta': 1,
'is': 1,
'bad': 1,
'good': 0,
'and': 0,
'expensive': 0
},
{
'Pasta': 1,
'is': 2,
'bad': 0,
'good': 1,
'and': 1,
'expensive': 1
}
}
答案 0 :(得分:1)
尝试一下:
def count_items(dic, lst):
counts = dict(dic)
for x in lst:
counts[x] += 1
return counts
lista=[['Pasta', 'is', 'bad'],['Pasta', 'is', 'good', 'and','is','expensive']]
dica={'Pasta': 0,'is': 0,'bad': 0,'good': 0,'and': 0,'expensive': 0}
print([count_items(dica, lista[0]), count_items(dica, lista[1])])
# prints [{'Pasta': 1, 'is': 1, 'bad': 1, 'good': 0, 'and': 0, 'expensive': 0}, {'Pasta': 1, 'is': 2, 'bad': 0, 'good': 1, 'and': 1, 'expensive': 1}]
(此解决方案假定fin_dict是一个列表,而输入列表中的所有项目都在字典中。)
答案 1 :(得分:0)
我在以下脚本中解释了详细信息:
lista=[['Pasta', 'is', 'bad'],['Pasta', 'is', 'good', 'and','is','expensive']]
dica={'Pasta': 0,'is': 0,'bad': 0,'good': 0,'and': 0,'expensive': 0}
# Create an empty array to store dictionaries.
myList = []
for i in range(len(lista)):
# Append `dica` in each iteration to get a reference of it.
myList.append(dica)
# Iterate through `dica` keys.
for key in dica:
# Iterate through list elements in lista.
for listElem in lista[i]:
# Check if the `key` is equal to the value in list,
# in other words, count the occurences of list elements.
if key == listElem:
myList[i][key] += 1
print(myList)
注意:据我所知,您所请求的输出类型是不可能的,我还认为您并不想使用dictionary
,因此我将其输出为list
。
输出:
[{'Pasta': 2, 'is': 3, 'bad': 1, 'good': 1, 'and': 1, 'expensive': 1}, {'Pasta': 2, 'is': 3, 'bad': 1, 'good': 1, 'and': 1, 'expensive': 1}]