使用该范围内的数字之和替换列表中的一系列数字(Python)

时间:2016-03-16 13:34:57

标签: python list

我正在尝试用该范围内的数字之和替换列表中的一系列数字。注意,我不想替换整个列表,只替换该列表中的特定范围。

这是我的代码:

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)。但我只想显示这笔钱。

谢谢!

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案:

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。在上面的代码中处理此问题的(差)quickfix仅在i仅包含一个值时附加。我不知道你打算用这个代码做什么,但我猜想合理的改进是调整nodes_listnew_dict和/或O_D_list的结构。

输出:

[[1, 250], [2, 100], [3, 0]]
相关问题