循环中的条件期间为变量赋值

循环中的条件期间为变量赋值

本文介绍了Python 在 while 循环中的条件期间为变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个关于 Python 语法的简单问题.我想在 while 循环的条件期间将一个函数的值分配给一个变量.当函数返回的值为 false 时,循环应该中断.我知道如何在 PHP 中做到这一点.

A simple question about Python syntax. I want to assign a value from a function to a variable during the condition for a while loop. When the value returned from the function is false, the loop should break. I know how to do it in PHP.

while (($data = fgetcsv($fh, 1000, ",")) !== FALSE)

但是,当我在 Python 中尝试类似的语法时,出现语法错误.

However when I try a similar syntax in Python I get a syntax error.

推荐答案

不能在表达式中使用赋值.赋值本身就是一个语句,不能组合 Python 语句.

You cannot use assignment in an expression. Assignment is itself a statement, and you cannot combine Python statements.

这是语言设计者的明确选择;很容易不小心使用一个 = 并赋值,而您打算使用两个 == 并测试相等性.

This is an explicit choice made by the language designers; it is all too easy to accidentally use one = and assign, where you meant to use two == and test for equality.

将赋值移到循环中,或者在循环之前赋值,并在循环本身中赋值.

Move the assignment into the loop, or assign before the loop, and assign new values in the loop itself.

对于您的具体示例,Python csv 模块 为您提供了更高级别的 API,而您将在 csv.reader() 上循环:

For your specific example, the Python csv module gives you a higher-level API and you'd be looping over the csv.reader() instead:

with open(csvfilename, 'rb') as csvfh:
    reader = csv.reader(csvfh)
    for row in reader:

很少,如果有的话,需要在循环结构中赋值.通常有一种(好得多)更好的方法来解决手头的问题.

I rarely, if ever, need to assign in a loop construct. Usually there is a (much) better way of solving the problem at hand.

也就是说,从 Python 3.8 开始,该语言实际上将具有赋值表达式,使用 := 作为赋值运算符.请参阅PEP 572.赋值表达式实际上在列表推导中很有用,例如,当您需要在正在构建的列表中包含一个方法返回值并且需要能够在测试中使用该值时.

That said, as of Python 3.8 the language will actually have assignment expressions, using := as the assignment operator. See PEP 572. Assignment expressions are actually useful in list comprehensions, for example, when you need to both include a method return value in the list you are building and need to be able to use that value in a test.

现在,您必须使用生成器表达式:

Now, you'd have to use a generator expression:

absolute = (os.path.abspath(p) for p in files)
filtered = [abs for abs in absolute if included(abs)]

但是使用赋值表达式你可以内联 os.path.abspath() 调用:

but with assignment expressions you can inline the os.path.abspath() call:

filtered = [abs for p in files if included(abs := os.path.abspath(p))]

这篇关于Python 在 while 循环中的条件期间为变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 19:06