我有一个问题,我想添加一些数学并为字典列表添加值。
distance_travelled_by_each_node = {0: [0.0, 17.751, 594.24, 1394.3, 2042.442, 2086.694], 1: [0.0,
1870.058, 2299.614, 3584.593, 3838.359, 4638.419, 5286.561, 5368.107, 5792.431,
6285.873, 6500.971, 6524.217, 13880.759000000002, 14049.589000000002], 2: [0.0,
648.142, 729.6880000000001, 1154.0120000000002, 1647.4540000000002,
1862.5520000000001, 1885.7980000000002, 9242.340000000002, 9411.170000000002]}
法典
arrival_time_at_each_node = {}
for i in range(len(distance_travelled_by_each_node)):
for j in range(len(distance_travelled_by_each_node[i])):
arrival_time_at_each_node[i].append(distance_travelled_by_each_node[i][j]/20)
键错误: 0
我期望的输出:
arrival_time_at_each_node = {0:[0.0, 0.8875500000000001, 29.712, 69.715, 102.1221,
104.3347],1:[ 0.0, 93.5029, 114.9807, 179.22965, 191.91795, 231.92095,
264.32804999999996,268.40535, 289.62154999999996, 314.29364999999996, 325.04855,
326.21085, 694.0379500000001,702.47945],2:[ 0.0, 32.4071, 36.48440000000001,
57.70060000000001, 82.37270000000001, 93.1276, 94.28990000000002, 462.1170000000001,
470.5585000000001]}
您使用的是字典而不是列表!您可以先获取不同的键,然后再获取值。另外不要忘记在新词典中启动列表。
这应该做:
arrival_time_at_each_node = {}
for key in distance_travelled_by_each_node.keys():
arrival_time_at_each_node[key] = []
for j, value in enumerate(distance_travelled_by_each_node[key]):
arrival_time_at_each_node[key].append(value/20)
使用字典理解:
arrival_time_at_each_node = {k: [x/20 for x in v] for k,v in distance_travelled_by_each_node.items()}
另一种可能性是,使用defaultdict
而不是普通dict
:
from collections import defaultdict
arrival_time_at_each_node = defaultdict(list)
由于这一行,你会得到一个KeyError
。
arrival_time_at_each_node[i].append(distance_travelled_by_each_node[i][j]/20)
因为当您尝试追加到其值时,arrival_time_at_each_node
中没有键0
。
但是,您可以尝试这种方式。
distance_travelled_by_each_node = {0: [0.0, 17.751, 594.24, 1394.3, 2042.442, 2086.694], 1: [0.0,
1870.058, 2299.614, 3584.593, 3838.359, 4638.419, 5286.561, 5368.107, 5792.431,
6285.873, 6500.971, 6524.217, 13880.759000000002, 14049.589000000002], 2: [0.0,
648.142, 729.6880000000001, 1154.0120000000002, 1647.4540000000002,
1862.5520000000001, 1885.7980000000002, 9242.340000000002, 9411.170000000002]}
arrival_time_at_each_node = {}
for i,v in distance_travelled_by_each_node.items():
arrival_time_at_each_node[i] = [x/20 for x in v]
print(arrival_time_at_each_node)
{0: [0.0, 0.8875500000000001, 29.712, 69.715, 102.1221, 104.3347], 1: [0.0, 93.5029, 114.9807, 179.22965, 191.91795, 231.92095, 264.32804999999996, 268.40535, 289.62154999999996, 314.29364999999996, 325.04855, 326.21085, 694.0379500000001, 702.47945], 2: [0.0, 32.4071, 36.48440000000001, 57.70060000000001, 82.37270000000001, 93.1276, 94.28990000000002, 462.1170000000001, 470.5585000000001]}