繁体   English   中英

将列表中的数字范围替换为该范围内的数字总和(Python)

[英]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
  • 在你的代码继续添加值nodeslist [0],因为你遍历nodes_list每次从进入一个新的键值对的时间new_dict 在上面的代码中解决此问题的(较差)快速解决方案是仅在i仅包含一个值的情况下追加。 我不知道您打算用这段代码做什么,但是我想一个合理的改进将是调整nodes_listnew_dict和/或O_D_list

输出:

[[1, 250], [2, 100], [3, 0]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM