【问题标题】:Check arrays of dictionaries for key-value pair and update another list accordingly检查字典数组的键值对并相应地更新另一个列表
【发布时间】: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


    【解决方案1】:

    您可以创建一个字典,将情绪映射到数组索引到计数的字典映射,这样您就可以遍历 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]
    

    【讨论】:

    • 正是我正在寻找的......是的,neu_list 的预期输出有问题,现在已经更正了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多