我有多个包含字典的数组。我想检查这些数组,并根据在数组中迭代字典时遇到的键值对更新另一个列表。
因此,对于以下4个情感数组:
senti_array1 = [{'senti':'Positive', 'count':15}, {'senti':'Negative', 'count':10}, {'senti':'Neutral', 'count':5}]
senti_array2 = [{'senti':'Positive', 'count':8}, {'senti':'Negative', 'count':4}]
senti_array3 = [{'senti':'Positive', 'count':2}]
senti_array4 = [{'senti':'Negative', 'count':7}, {'senti':'Neutral', 'count':12}]
pos_list=[]
neg_list=[]
neu_list=[]如果它们是一个负面情绪,则在这种情况下,应使用其计数值更新相应的列表(neg_list),否则,如果数组中不存在‘负面’情绪,则应在列表中追加0。
最终输出应为:
pos_list=[15, 8, 2, 0]
neg_list=[10, 4, 0, 7]
neu_list=[5, 0, 0, 12]我尝试使用normal for循环,但没有得到所需的输出,因为每次检查if else条件时,如果情绪不存在,则在列表中附加一个0,这会产生错误的输出。我认为map或lambda函数可以用于此目的,但不知道如何开始。
发布于 2019-03-03 23:07:38
您可以创建一个字典,将情感映射到数组索引到计数的字典映射,这样您就可以遍历这3个情感,并在数组数量的范围内迭代索引,以构建计数列表。使用dict.get方法将默认计数设置为0:
mapping = {}
for i, l in enumerate((senti_array1, senti_array2, senti_array3, senti_array4)):
for d in l:
mapping.setdefault(d['senti'], {})[i] = d['count']
pos_list, neg_list, neu_list = ([mapping.get(s, {}).get(k, 0) for k in range(i + 1)] for s in ('Positive', 'Negative', 'Neutral'))给定您的示例输入,pos_list将变为:
[15, 8, 2, 0]neg_list变成:
[10, 4, 0, 7]而neu_list变成了:
[5, 0, 0, 12]https://stackoverflow.com/questions/54969923
复制相似问题