python - 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。
解决方案
您可以创建一个空字典,然后遍历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)
推荐阅读
- swiftui - 没有披露指示器的 SwiftUI NavigationButton?
- javascript - 更新 Vuex 商店中二维数组中的项目
- c - 如何在risc-v中实现printf函数?
- docker - Stilliard/pure-ftpd:允许其他 docker 容器的 ftp?
- c++ - 这两个中哪一个是实现标头的正确方法?
- c - 父进程在挂起时仍然收到信号
- python - 为什么我的 Python 正则表达式不匹配查询字符串的一部分?
- amazon-web-services - %matplotlib 内联魔术命令无法从 AWS-EMR Jupyterhub Notebook 中的先前单元格读取变量
- javascript - 如何将程序从从 onload 开始更改为从 Space press 开始?
- android - 为什么应用程序的所有本地化都不起作用?