繁体   English   中英

在用作条件的 elif 语句之前定义新变量

[英]Defining new variable before elif statement that is used as a condition

我正在尝试使用if-elif-else语句定义某种逻辑。 但在我看来似乎合乎逻辑的东西似乎是无效的语法。 我真的不明白为什么。 我想对此有一个相当简单的答案。

我写了一些逻辑如下:

mylist = ['a', 'aa', 'aaa']

for index, element in enumerate(mylist):
    if index == len(mylist)-1:
        # Case: this is the last element
        pass

    myvar = mylist[index+1]
    elif len(myvar) == 2:
        # Case: this is not the last element and the next element length is 2
        pass

    else:
        # Case: this is not the last element and the next element length is not 2 ()
        pass

问题在于myvar的定义和随之而来的elif语句。 此代码给出了无效的语法,pycharm 将其定义为“变量注释的非法目标”。 问题是:为什么不能在elif语句之前定义myvar 即使代码可能无法到达某个elif语句,是否必须在执行语句之前预定义所有条件? 或者if-elif-else部分之间根本不能有任何额外的代码? 在这种情况下,无法预定义myvar ,因为它可能超出范围。

作为一个解决方案,我这样做了:

for index, element in enumerate(mylist):
    if index == len(mylist) - 1:
        # Case: this is the last element
        pass
    else:
        myvar = mylist[index + 1]
        if len(myvar) == 2:
            # Case: this not the last element and the length of next element is 2
            pass

        else:
            # Case: this is not the last element and the length of next element is not 2
            pass

是的,在if-elif-else之间不能有任何额外的代码。 所以你应该把myvar放在if-elif-else之前。

for index, element in enumerate(mylist):
    myvar = mylist[index+1]
    if index == len(mylist) - 1:
        pass
    elif len(myvar) == 2:
        pass

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM