[英]Replace a range of numbers in a list with the sum of numbers in that range (Python)
我试图用该范围内的数字总和替换列表中的数字范围。 注意,我不想替换整个列表,而只替换列表中的特定范围。
这是我的代码:
nodes_list = [[1], [2], [3]]
new_dict = {1: [1], 2: [1, 2], 3: [1, 3]}
O_D_list = [[1, 1, 0], [1, 2, 100], [1, 3, 150]]
b = max(new_dict)
for key in new_dict:
for i in nodes_list:
if i[0] in new_dict[key]:
i.append(sum(O_D_list[b-1][2]))
#this is where I am stuck. I would like to get the SUM of the numbers in range O_D_list[b-1][2] and then append only that sum to nodes_list.
b -= 1
print ('nodes list', nodes_list)
print ('O_D_list', O_D_list)
print ('b', b)
这是我的输出:
File "location", line 13, in <module>
i.append(sum(O_D_list[b-1][2]))
TypeError: 'int' object is not iterable
我想要的输出是:
nodes_list = [[1, 250], [2, 100], [3, 0]]
如果从第13行中删除“ sum()”,则会得到以下输出:
nodes list [[1, 150, 100, 0], [2, 100], [3, 0]]
O_D_list [[1, 1, 0], [1, 2, 100], [1, 3, 150]]
b 0
因此,我知道我希望nodes_list[0][1]
等于250:(150 + 100)。 但我只想显示这笔款项。
谢谢!
一种可能的解决方案:
nodes_list = [[1], [2], [3]]
new_dict = {1: [1], 2: [1, 2], 3: [1, 3]}
O_D_list = [[1, 1, 0], [1, 2, 100], [1, 3, 150]]
b = max(new_dict)
for key,value in new_dict.items():
for i in nodes_list:
if i[0] in value and len(i)==1:
i.append(sum((x[2] for x in O_D_list[:b])))
b -= 1
解释代码:
b
个子列表生成子列表中索引为2的所有值的伪列表。 然后将其相加并添加到列表i
。 nodes_list
每次从进入一个新的键值对的时间new_dict
。 在上面的代码中解决此问题的(较差)快速解决方案是仅在i
仅包含一个值的情况下追加。 我不知道您打算用这段代码做什么,但是我想一个合理的改进将是调整nodes_list
, new_dict
和/或O_D_list
。 输出:
[[1, 250], [2, 100], [3, 0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.