遍历一个空列表

-2 python for-loop

尝试迭代基于先前条件的列表,该列表可能为空也可能不是空。

这是代码:

function_name(): 
    for x in gen:
        if x = attacker1:
            gain += 2
        elif x = attacker2:
            gain += 3
        else:
            gain -= 1
    if not gen:
        gain -= 1
    return gain
Run Code Online (Sandbox Code Playgroud)

当列表中存在变量之一时,代码将起作用。当没有变量存在时,代码不起作用,并且我收到以下错误消息:

错误消息:分配前已引用局部变量“增益”

我也尝试过:

function_name():      
      for x in gen:
          if x = attacker_1:
              gain += 2
          elif x = attacker2:
              gain += 3
          else:
              gain -= 1
      if gen == False:
          gain -= 1
      return gain
Run Code Online (Sandbox Code Playgroud)

上面的代码给了我同样的错误信息。

另外,不确定在for循环中是否需要“ else”语句,但是为了安全起见,我将其放入其中。

任何帮助深表感谢。谢谢!

小智 5

没有在任何地方声明收益,所以你做不到

gain += 2
Run Code Online (Sandbox Code Playgroud)

因为您不能将2加到尚不存在的内容上。

所以你必须写

gain = 0
Run Code Online (Sandbox Code Playgroud)

在您的职能开始时。

该错误信息非常有用。