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

时间:2015-11-01 00:28:10

标签: python python-3.x for-loop

基本上,这就是我想要做的。我有一个使用Python 3读取的CSV文件。所以,这是行的基本布局:

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

访问它的代码是:

for row in file:
     var = row[0]
     print(var)

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

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'.

希望这个问题有道理。我不确定如何在Python 3中执行此操作。

2 个答案:

答案 0 :(得分:1)

# 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"非空字符串是“真实的”。通过使用语句if row:,当if包含非空字符串时,我们只会进入row语句,例如"On""Off"

答案 1 :(得分:0)

一个简单的if / else会做

var = some_initial_value
for row in file:
     var = row[0] if row[0] else var
     print(var)