【问题标题】:How to use the result of a function call as condition of the loop and in the body of the loop?如何将函数调用的结果用作循环的条件和循环体?
【发布时间】:2022-09-27 22:19:54
【问题描述】:

以下概念适用于 C 和 C++ 语言,您将函数的结果分配给变量,然后使用新分配的变量作为 while 循环的条件。所以使用comma operator

一段 C++ 代码示例如下所示。我通过从数组中进行赋值来模拟函数调用的行为。在我的实际情况下,该函数仅提供一次值,我想将其用作条件,但也用于 while 主体循环。我没有其他可用的结束条件。

#include <iostream>

int main(){
    int vals[] = {1, 2, 3, 4};

    int var = 0;
    int i=0;
    while(var = vals[i], var != 3){ // vals mocks the function
        std::cout << var << std::endl; // mock usage of value stored in var
        i++;
    }
}

获取函数调用结果、在循环中将其用作条件并在循环体中使用它的 pythonic 方式是什么?在其他语言中,do-while 循环可以解决这个问题,但 python 没有。

  • 所谓的“海象算子”(在 3.8 中引入)非常适合这种情况
  • @弗拉德,超级!还不错的是,运算符的名称比 \'comma\' 更好(可搜索)。

标签: python python-3.x


【解决方案1】:

所谓的“海象算子”(在 3.8 中引入)非常适合这一点。

这是一个例子:

def func():
    return 1 # obviously not a constant

while (n := func()) != 0:
    print(n) # infinite loop in this example but you get the point

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 2020-09-02
    • 2018-11-27
    • 2021-09-15
    相关资源
    最近更新 更多