python-3.x - 匹配条件时合并多个相同长度的列表

标签 python-3.x

给定输入:theList = [<userID>,<number_of_views>]

theList = [
    [[3, 5], [1, 1], [2, 3]],
    [[1, 2], [3, 5], [3, 0], [2, 3], [4, 2]],
    [[1, 2], [3, 5], [3, 0], [2, 3], [4, 2]],
    [[1, 2], [1, 1], [4, 2]]
]

expected output = [
    [[3, 5], [2, 3], [1, 1]],
    [[3, 5], [2, 3], [1, 2], [4, 2]],
    [[3, 5], [2, 3], [1, 2], [4, 2]],
    [[1, 3], [4, 2]]
]

for sublist in theList:

e.x -->

theList[3] = [[1,2], [1,1], [4,2]]

在这种情况下如何合并具有相同 userIDs = 1 的项目,并将所有对应的 View 与此 (userID=1) (2+1) = 3 个 View 相加到一个新列表中 --> [1,3]

expected theList[3] = [[1,3], [4,2]].

我如何为所有 theList 执行此过程?

非常感谢您花时间回答这个问题!

最佳答案

这是一种使用 collections.defaultdict 的方法。

例如:

from collections import defaultdict

theList = [
    [[3, 5], [1, 1], [2, 3]],
    [[1, 2], [3, 5], [3, 0], [2, 3], [4, 2]],
    [[1, 2], [3, 5], [3, 0], [2, 3], [4, 2]],
    [[1, 2], [1, 1], [4, 2]]
]

result = []
for i in theList:
    r = defaultdict(int)
    for j, k in i:
        r[j] += k
    result.append(list(r.items()))

print(result)

输出:

[[(3, 5), (1, 1), (2, 3)],
 [(1, 2), (3, 5), (2, 3), (4, 2)],
 [(1, 2), (3, 5), (2, 3), (4, 2)],
 [(1, 3), (4, 2)]]

关于python-3.x - 匹配条件时合并多个相同长度的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57622583/

相关文章:

python-3.x - 无法获取缺少的 termios 模块。我如何正确获得它?

python - Alien 类没有 rect 属性

python - 我是 Python 新手,在向程序添加一行代码后设法使 IDLE 崩溃

Python 信用卡验证

Python 3 打印utf-8 编码字符串问题

python - 我之前在脚本中定义的函数出现名称错误

python - 从字符串创建一个字典,每个字符都是键和值

python-3.x - 在 panda 数据框中检测星期六并修改行中的值

python - 想要将嵌套字典作为单个记录写入 SQL 表中(错误 : Not enough parameters for the SQL statement )

python:变量在几个条件之后没有被定义