Python for 循环迭代

标签 python loops dictionary

我试图在使用循环时填充字典,问题是循环在满足条件后停止而不检查是否有更多可用条件要满足,

sec=[
     [1, 2, 4.0, 100.0], 
     [2, 3, 1.5, 500.0], 
     [2, 4, 10.0, 700.0], 
     [2, 5, 5.75, 1500.0], 
     [3, 4, 11.4, 200.0], 
     [4, 5, 10.5, 750.0], 
     [4, 6, 6.75, 550.0]]

我列出了这个列表,还有这本字典

graph={1: [1], 2: [2], 3: [3], 4: [4], 5: [5], 6: [6]} 我想要完成的是

graph = {1: ['2'],
         2: ['3', '4','5'],
         3: ['4'],
         4: ['5','6'],
         5: [],
         6: []}

它应该如何工作是它收集所有 sec[x][0] 作为字典的键和 sec[n][1] 作为字典的键字典中的值 如果 sec[x][0] 的值为 1 且 sec[x][1] 的值为 2,则将数字 2 添加到字典中作为键 1 的值 我得到的代码是这样的

def magic(numList): #turns string into int
   s = ''.join(map(str, numList))
   return int(s)
for i in range(1,len(loc)+1): #len of loc is 6
    for n in range(0,len(loc)+1):
        if magic(graph[i])==sec[n][0]:
            graph[i].append(sec[n][1])

但它只会添加第一个值,然后索引 n 将停止计数,然后索引 i 继续计数,因此它不会检查键中的更多值

最佳答案

您对 graph 的初始定义对预期结果没有帮助。使用空列表初始化值,然后附加到一个简单的循环中:

>>> sec=[
     [1, 2, 4.0, 100.0], 
     [2, 3, 1.5, 500.0], 
     [2, 4, 10.0, 700.0], 
     [2, 5, 5.75, 1500.0], 
     [3, 4, 11.4, 200.0], 
     [4, 5, 10.5, 750.0], 
     [4, 6, 6.75, 550.0]]
>>> graph = {i:[] for i in range(1,7)}
>>> for x,y,*z in sec: graph[x].append(str(y))

>>> graph
{1: ['2'], 2: ['3', '4', '5'], 3: ['4'], 4: ['5', '6'], 5: [], 6: []}

关于Python for 循环迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41409537/

相关文章:

python - Django simple_tag 和设置上下文变量

java - 关于sizeof的问题。我想反转数字中的位

c++ - 带有 try catch 和异常抛出的方法

c++ - 使用 long double 还是仅使用 double 来计算 pi?

Python argparse 参数 : issue with passing strings containing hyphens

python - 如何在 Google App Engine Python 应用程序的模块之间共享 session ?

python - 为什么基类在多重继承中不起作用?

python - 如何防止通过 for 循环覆盖字典中的数据

python - 删除 Python 中可能存在或不存在的字典属性

ios - 无法将排序的字典序列化为 JSON - Swift 3