我有以下2d列表和字典:
List2d = [['1', '55', '32', '667' ],
['43', '76', '55', '100'],
['23', '70', '15', '300']]
dictionary = {'New York':0, "London": 0, "Tokyo": 0, "Toronto": 0 }
如何用List2d中列的和替换字典的所有值?所以字典会是这样的:
dictionary= {'New York' : 67, 'London': 201, 'Tokyo': 102, 'Toronto': 1067}
#67 comes from adding up first column (1+43+23) in 'List2d'
#201 comes from adding up second column (55+76+70) in 'List2d'
#102 comes from adding up third column (32+55+15) in 'List2d'
#1067 comes from adding up fourth column (667+100+300) in 'List2d'
发布于 2020-11-26 18:35:49
从Python3.7开始,dict中的键是有序的。
您可以使用枚举,以便在迭代过程中跟踪元素在dict中的位置。然后,将i
用作2d列表中每一行的索引,将每个值转换为int,并对结果进行求和。
List2d = [['1', '55', '32', '667' ],
['43', '76', '55', '100'],
['23', '70', '15', '300']]
dictionary = {'New York':0, "London": 0, "Tokyo": 0, "Toronto": 0 }
for i, city in enumerate(dictionary.keys()):
dictionary[city] = sum(int(row[i]) for row in List2d)
print(dictionary)
# {'New York': 67, 'London': 201, 'Tokyo': 102, 'Toronto': 1067}
发布于 2020-11-26 18:35:50
利用熊猫
#!pip install pandas
import pandas as pd
pd.DataFrame(List2d, columns=dictionary.keys()).astype(int).sum(axis=0).to_dict()
产出:
{'New York': 67, 'London': 201, 'Tokyo': 102, 'Toronto': 1067}
https://stackoverflow.com/questions/65027529
复制相似问题