python 将两个不同的列表合并为一个

标签 python

我得到了两次不同的测试,测试分数也不同。 我将这两个测试存储在单独的列表中。如何合并两个列表并获得最终结果?

returnn = sorted(returnscore, key=itemgetter('score'), reverse=True) 
for rij in returnn:
    print rij

输出:

{'E-mail': 'tim@gmail.com', 'score': 10}
{'E-mail': 'tim@gmail.com', 'score': 10}
{'E-mail': 'tim@gmail.com', 'score': 10}
{'E-mail': 'tim@gmail.com', 'score': 10}
{'E-mail': 'hihallo@gmail.com', 'score': 5}
{'E-mail': 'noreply@com', 'score': 5}
{'E-mail': 'marketing@nl', 'score': 5}

spff = sorted(spfscore, key=itemgetter('score'), reverse=True) 
for rij in spff:
    print rij

输出:

{'E-mail': 'tim@gmail.com', 'score': 3}
{'E-mail': 'tim@gmail.com', 'score': 0}
{'E-mail': 'tim@gmail.com', 'score': 7}
{'E-mail': 'tim@gmail.com', 'score': 0}
{'E-mail': 'hihallo@gmail.com', 'score': 0}
{'E-mail': 'noreply@com', 'score': 0}
{'E-mail': 'arketing@nl', 'score': 1}

我想要的输出是:

{'E-mail': 'tim@gmail.com', 'score': 50}
{'E-mail': 'hihallo@gmail.com', 'score': 5}
{'E-mail': 'noreply@com', 'score': 5}
{'E-mail': 'arketing@nl', 'score': 6}

我花了几个小时试图解决这个问题。我只是不明白 我如何计算分数并删除重复的分数。

最佳答案

解决此问题的一个简单方法是简单地创建一个新的 dict 对象,其中包含电子邮件地址作为其(唯一)键,然后迭代列表,如果该元素已在列表中,则增加分数计数列表,或者如果电子邮件地址尚未在字典中,则创建带有分数计数的字典条目。

scores_raw = [{'E-mail': 'tim@gmail.com', 'score': 10},
{'E-mail': 'tim@gmail.com', 'score': 10},
{'E-mail': 'tim@gmail.com', 'score': 10},
{'E-mail': 'tim@gmail.com', 'score': 10},
{'E-mail': 'hihallo@gmail.com', 'score': 5},
{'E-mail': 'noreply@com', 'score': 5},
{'E-mail': 'marketing@nl', 'score': 5}]

scores_unique = {}
for item in scores_raw:
    if item['E-mail'] not in scores_unique:
        scores_unique.update({item['E-mail']: item['score']})
    else:
        scores_unique[item['E-mail']] += item['score']

print (scores_unique)

输出:{'tim@gmail.com': 40, 'hihallo@gmail.com': 5, 'noreply@com': 5, 'marketing@nl': 5}

关于python 将两个不同的列表合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46645753/

相关文章:

python - 列表理解之谜 - Python

python - 如何通过先前 xpath 搜索的结果执行 lxml xpath 搜索?

python - 尝试在 jupyter 笔记本中打印数据帧时出现类型错误

Python TemporaryDirectory 在 "with"语句中使用时返回字符串

python - 将图像从 python 传输到 C++ 并返回

python - 如何理解 PyMC 模型中 `yield` 的使用?

Python:字符串连接对象的多个属性

python - 在 Python 中围绕匹配项添加标签

python - Gensim 3.8.0 到 Gensim 4.0.0

python - 从函数式 API 模型上的 Keras CNN Predict() 获取概率