【发布时间】:2019-03-03 23:24:43
【问题描述】:
我有多个包含字典的数组。我想检查这些数组并根据在数组中迭代字典时遇到的键值对更新另一个列表。
所以对于以下 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]
我尝试使用正常的 for 循环,但我没有得到所需的输出,因为每次检查 else 条件时,如果情绪不存在,则会在列表中附加一个 0,这会产生错误的输出。我认为可以使用地图或 lambda 函数,但不知道如何开始。
【问题讨论】:
标签: python list dictionary