如何在For循环期间跟踪变量?

2024-05-03 05:12:17 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,这就是我要做的。我有一个用python3读入的CSV文件。下面是行的基本布局:

Row1: On
Row2: <empty>
Row3: <empty>
Row4: On
Row5: On
Row6: <empty>
Row7: Off
Row8: <empty>

访问的代码是:

^{pr2}$

运行脚本后,我希望看到每行的输出是:

for row in file:
     print(var)

On
On
On
On
On
On
Off
Off

我不知道该怎么做,但我试图在程序通过for循环时跟踪变量。逻辑如下:

for loop:
  1.  If row[0] has the string 'On', then assign 'On' to var
  2.  If the next row[0] is empty, then I want the var to retain the previous value of 'On'.
  3.  Var will not change from 'On' until row[0] has a different value such as 'Off'.  Then, Var will be assigned 'Off'.

希望这个问题有意义。我不知道如何在Python3中实现这一点。在


Tags: thetoforifvalueonvarwill
2条回答

简单的if/else就可以了

var = some_initial_value
for row in file:
     var = row[0] if row[0] else var
     print(var)
# set an initial value for `var`
var = None
for row in file:
    # `row` should now contain the text content of a line
    if row:
        # if the string is not empty
        # set var to the value of the string
        var = row
    # print the value of var
    print(var)

在Python中,empty strings are "falsey"而非空字符串是“truthy”。通过使用if row:语句,我们只会在row包含非空字符串(如"On")或{}时继续执行if语句。在

相关问题 更多 >