如何在Python中的while(表达式)循环中进行变量赋值?

2024-04-25 02:06:31 发布

您现在位置:Python中文网/ 问答频道 /正文

变量赋值是为了返回赋值,并直接在while循环中将其与空字符串进行比较。

以下是我在PHP中的使用方法:

while((name = raw_input("Name: ")) != ''):
    names.append(name)

我要做的是在功能上与此相同:

names = []
while(True):
    name = raw_input("Name: ")
    if (name == ''):
        break
    names.append(name)

在Python中有什么方法可以做到这一点吗?


Tags: 方法字符串name功能trueinputrawif
3条回答

不,对不起。这是一个常见问题,在这里解释得很好:

Pydocs,和Fredrik Lundh's blog

The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages.

Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.

An interesting phenomenon is that most experienced Python programmers recognize the while True idiom and don’t seem to be missing the assignment in expression construct much; it’s only newcomers who express a strong desire to add this to the language.

There’s an alternative way of spelling this that seems attractive:

line = f.readline() while line:
    ... # do something with line...
    line = f.readline()

您可以将raw_input()包装成生成器:

def wrapper(s):
    while True:
        result = raw_input(s)
        if result = '': break
        yield result

names = wrapper('Name:')

这意味着我们回到了原点,但代码更复杂。因此,如果需要包装现有方法,则需要使用nosklo的方法。

from functools import partial

for name in iter(partial(raw_input, 'Name:'), ''):
    do_something_with(name)

或者如果你想要一个列表:

>>> names = list(iter(partial(raw_input, 'Name: '), ''))
Name: nosklo
Name: Andreas
Name: Aaron
Name: Phil
Name: 
>>> names
['nosklo', 'Andreas', 'Aaron', 'Phil']

相关问题 更多 >