首页 > 解决方案 > Python 2D 列表到字典

问题描述

我有一个二维列表,必须从二维列表中获取 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。

标签: pythonmachine-learning

解决方案


您可以创建一个空字典,然后遍历groupby. 如果groupby字典中存在 in 的元素,则将对应的元素添加到columns字典中的值中。否则,将 in 中的元素添加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)

否则,如果您想保留初始 avgdict,则可以将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)

推荐阅读