如何在 Python 的 while(expression) 循环中进行变量赋值? [英] How to do variable assignment inside a while(expression) loop in Python?

查看:35
本文介绍了如何在 Python 的 while(expression) 循环中进行变量赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了变量赋值,以便直接在 while 循环中返回分配的值并将其与空字符串进行比较.

这是我在 PHP 中的做法:

while((name = raw_input("Name: ")) != ''):名称.附加(名称)

我正在尝试做的功能与此相同:

names = []而(真):name = raw_input("姓名:")如果(名称 == ''):休息名称.附加(名称)

有没有办法在 Python 中做到这一点?

解决方案

from functools import partial对于 iter(partial(raw_input, 'Name:'), '') 中的名称:do_something_with(name)

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

<预><代码>>>>名称 = 列表(迭代器(部分(原始输入,'名称:'),''))名称:诺斯洛姓名:安德烈亚斯姓名:阿龙姓名:菲尔名称:>>>名字['nosklo', 'Andreas', 'Aaron', 'Phil']

I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop.

Here is how I'm doing it in PHP:

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

What I'm trying to do is identical to this in functionality:

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

Is there any way to do this in Python?

解决方案

from functools import partial

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

or if you want a list:

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

这篇关于如何在 Python 的 while(expression) 循环中进行变量赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆