【问题标题】:How to get variable out of a nested loop?如何从嵌套循环中获取变量?
【发布时间】:2021-04-07 21:26:39
【问题描述】:

我的问题很简单,如何从这个嵌套循环中获取结果变量:

for row in new_matrix:
    for col in row:
        if col == 'S':
            result = [(new_matrix.index(row), row.index(col))]

我尝试在上面分配一个全局变量 result 并将其设置为等于此表达式 [(new_matrix.index(row), row.index(col))] 但它不起作用,我想不使用 global 这样做,因为这是不好的做法

【问题讨论】:

  • 从函数中返回。
  • 如果不想再看下去,就用break结束循环
  • @JurajBezručka 无法打破 嵌套 循环。
  • 另外你的第二个 for 循环没有正确缩进。
  • 将默认值分配给变量,然后在(嵌套)循环中更改它并不是要避免全局变量——这些变量是定义在函数或方法之外的变量 i> 其值在一个内部发生变化。这里有更多information。换句话说,您的代码基本上没问题,只是在进入循环之前为变量分配了一个初始值,在您的情况下这不起作用,因为 rowcol 仅在其中定义。解决方法是简单地使用None

标签: python loops variables


【解决方案1】:

列表在 python 中是可变的,所以你可以这样做:

result = []
for row in new_matrix:
   for col in row:
      if col == 'S':
         result.append(new_matrix.index(row), row.index(col))

【讨论】:

    【解决方案2】:
    def your_function():
        for row in new_matrix:
            for col in row:
                if col == 'S':
                    return [(new_matrix.index(row), row.index(col))]
    
    result = your_function()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-25
      • 1970-01-01
      • 2013-03-15
      • 2014-11-05
      • 2018-06-11
      • 1970-01-01
      相关资源
      最近更新 更多