Python 2D列表到字典

标签 python machine-learning

我有一个二维列表,必须从二维列表中获取 2 列,并将每列中的值作为键:值对放置。

示例:

table = [[15, 29, 6, 2],
        [16, 9, 8, 0],
        [7, 27, 16, 0]]

def averages(table, col, by):

    columns = tuple(([table[i][col] for i in range(len(table))]))  #Place col column into tuple so it can be placed into dictionary
    groupby = tuple(([table[i][by] for i in range(len(table))]))   #Place groupby column into tuple so it can be placed into dictionary

    avgdict = {}
    avgdict[groupby] = [columns]
    print(avgdict)

averages(table, 1, 3)

输出是:

{(2, 0, 0): [(29, 9, 27)]}

我试图让输出相等:

{0:36, 2:29}

所以基本上 0 的 2 个键都添加了它们的值

我很难理解如何将每个键与其值分开 如果键相等,则将值相加。

编辑:我只使用 Python 标准库,并没有为这个问题实现 numpy。

最佳答案

您可以创建一个空字典,然后遍历 groupby 的每个元素。如果字典中存在 groupby 中的元素,则将 columns 中对应的元素添加到字典中的值中。否则,将groupby中的元素作为key,将columns中对应的元素作为value。实现如下:

table = [[15, 29, 6, 2],
    [16, 9, 8, 0],
    [7, 27, 16, 0]]

def averages(table, col, by):
    columns = tuple(([table[i][col] for i in range(len(table))]))  #Place col column into tuple so it can be placed into dictionary
    groupby = tuple(([table[i][by] for i in range(len(table))]))   #Place groupby column into tuple so it can be placed into dictionary

    avgdict = {}

    for x in range(len(groupby)):
        key = groupby[x]
        if key in avgdict:
            avgdict[key] += columns[x]
        else:
            avgdict[key] = columns[x]

    print(avgdict)

averages(table, 1, 3)

否则,如果你想保留你的初始平均数,那么你可以将 averages() 函数更改为

def averages(table, col, by):
    columns = tuple(([table[i][col] for i in range(len(table))]))  #Place col column into tuple so it can be placed into dictionary
    groupby = tuple(([table[i][by] for i in range(len(table))]))   #Place groupby column into tuple so it can be placed into dictionary

    avgdict = {}
    avgdict[groupby] = [columns]

    newdict = {}

    for key in avgdict:
        for x in range(len(key)):
            if key[x] in newdict:
                newdict[key[x]] += avgdict[key][0][x]
            else:
                newdict[key[x]] = avgdict[key][0][x]

    print(newdict)

关于Python 2D列表到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53292779/

相关文章:

Pythonic 累积图

python - 在此异步设置中,我在哪里捕获 KeyboardInterrupt 异常

image-processing - 如何测量用于图像检索的 Fisher 矢量之间的距离?

python - 如何根据 DCGAN 论文在扁平表示向量之上训练 L2-SVM 分类器

python - 如何返回多字典的键值?

python - 在 django 模板中显示外键值

python - 高效查找大型列表中的字符串不匹配

python - 你能找出这个关于线性回归的正规方程实现的程序有什么问题吗

python - 深度学习: Validation Loss Fluctuates Wildly Yet Training Loss is Stable

machine-learning - 使用 mlr3pipeline 编码和缩放后无法通过 mlr3proba 训练数据集