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