python - 循环迭代 0 中的变量传递到下一个循环等

标签 python loops if-statement for-loop

首先,对我糟糕的 Python 技能表示歉意 - 我是从一个平庸的 IDL 用户开始接触 Python 的,所以我知道我没有以最好的方式做事。

问题是,我正在对文件循环进行分析。我正在生成一个名为 so2c 的图像。对于该图像,我想找到该图像与其前一个图像之间的差异,因此只想在第一个图像之后的循环中执行此操作。然而,以下代码会引发错误“NameError:全局名称'so2dat'未定义”。我之前的代码是通过将所有图像存储到一个巨大的 numpy 数组中然后查找差异来工作的。然而,超过 150 张图像导致我的内存不足。感谢您的帮助:)

for files in files_list:

    fname1 = files
    .....do some more processing to generate an image array ([512,644]) called so2c

    if files_list.index(files)==0: 
        so2dat=so2c
        timea=times2
    else:
        sdiff= so2c-so2dat
        tdiff= times2-timea
        so2dat=so2c
        timea=times2

最佳答案

问题很简单。您正在定义 so2dat在你的if block ,并且您正在 else 中使用它堵塞。每次迭代只能输入一个 block ,而不能输入另一个 block 。因此,如果您输入 else在输入 if 之前阻止阻止您将不会执行 so2dat 的定义在你的if block 。

查看一个 super 简单的示例:

>>> for word in "foo bar baz".split():
        if word[0] == 'f':
            hello = "hello"
        else:
            print hello

hello
hello
>>> for word in "foo bar baz".split():
        if word[0] == 'b':
            blah = "blah"
        else:
            print blah

Traceback (most recent call last):
  File "<pyshell#25>", line 5, in <module>
    print blah
NameError: name 'blah' is not defined

输入 if 就不用担心了首先阻止,但如果您输入 else首先阻止,你会得到 NameError .

想一想,如果您试图确保输入 if仅在第一次迭代时阻止,您可以使用 enumerate 并使用其中的计数部分来检查您是否处于第一次迭代。或者,您可以执行类似的操作(只需从循环中删除第一个迭代,单独执行,然后循环 files_list 其余部分的一部分):

so2dat, timea = do_some_processing_on(files_list[0])
for files in files_list[1:]:
    fname1 = files
    so2c, times2 = do_some_processing_on(fname1)
    # what have you
    sdiff= so2c-so2dat
    tdiff= times2-timea
    so2dat=so2c
    timea=times2

关于python - 循环迭代 0 中的变量传递到下一个循环等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22540175/

相关文章:

c++ - 如何增强 C++ 数组在大规模访问时的性能

mysql - 当多个其他列为真时创建mysql sum列

php - 在用 PHP 中的 IF 语句更新 php 中的表内容之前如何检查?

if-statement - react 原生条件渲染

python - 如何在了解时间常数和稳态值的 gekko 中构建过程模拟器

python - 是否有将日期时间转换为 "5 hours ago"或 "12 days ago"的 Django 模板过滤器?

loops - assembly 错误 A2075 : jump destination too far : by 25 byte(s) on LOOP instruction

python - 我在 python 中分别导入和加载图像数据时遇到问题

python - 如何根据某些条件对单个可迭代对象进行 "round-robin"?

Python:查找从今天开始两个月开始的日期并从星期一开始