Python 2.7 如何创建一个嵌套在python中的字典,它将表示与特定作品相关的单词出现的次数?
我有这样一个清单:-Python 2.7 如何创建一个嵌套在python中的字典,它将表示与特定作品相关的单词出现的次数?,python-2.7,Python 2.7,我有这样一个清单:- new_list=[['happy', 'people', 'need', 'rest'], ['rest', 'apple', 'good', 'happy'],['kepler', 'people', 'happy', 'apple'],['need', 'good', 'happy', 'good']] 还有另一个类似的列表 a=['good', 'apple', 'people', 'rest', 'kepler', 'need', 'happy'] 它包含给定
new_list=[['happy', 'people', 'need', 'rest'], ['rest', 'apple', 'good', 'happy'],['kepler', 'people', 'happy', 'apple'],['need', 'good', 'happy', 'good']]
还有另一个类似的列表
a=['good', 'apple', 'people', 'rest', 'kepler', 'need', 'happy']
它包含给定的新_列表的不同单词数。
现在,我想遍历列表“a”中的每个元素,并在新列表中找到包含该元素的子列表,然后在这些子列表中,我想计算其中单词的出现率。例如,对于列表“a”中的单词“good”,新列表中包含“good”的子列表如下
现在计算这个列表中每个单词的出现率
{"good":{"rest":1,"apple":1,"happy":2,"need":1}}
类似地,我想要“a”列表中所有元素的总体输出。如何执行tht?您可以对s和ifs使用嵌套的
new_list=[['happy', 'people', 'need', 'rest'], ['rest', 'apple', 'good', 'happy'],['kepler', 'people', 'happy', 'apple'],['need', 'good', 'happy', 'good']]
a=['good', 'apple', 'people', 'rest', 'kepler', 'need', 'happy']
dct = {}
for item in a:
mid_dct = {}
for lst in new_list:
if item in lst: #checks if distinct item is in list
for word in lst: #iterates over that list to store words and their number of occurences
if word != item:
if word in mid_dct: #if that word in dct, adds one, if not adds that to list
mid_dct[word] += 1
else:
mid_dct[word] = 1
dct[item] = mid_dct
print dct
new_list=[['happy', 'people', 'need', 'rest'], ['rest', 'apple', 'good', 'happy'],['kepler', 'people', 'happy', 'apple'],['need', 'good', 'happy', 'good']]
a=['good', 'apple', 'people', 'rest', 'kepler', 'need', 'happy']
dct = {}
for item in a:
mid_dct = {}
for lst in new_list:
if item in lst: #checks if distinct item is in list
for word in lst: #iterates over that list to store words and their number of occurences
if word != item:
if word in mid_dct: #if that word in dct, adds one, if not adds that to list
mid_dct[word] += 1
else:
mid_dct[word] = 1
dct[item] = mid_dct
print dct