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

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

问题描述



我是这样做的,为了返回分配的值,并将其与空字符串进行比较,直接在while循环中。在PHP中执行:

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

我要做的是与功能相同:

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

在Python中有什么办法吗?

解决方案

 从functools import partial 

在iter中的名称(partial(raw_input,'Name:'),''):
do_something_with(name)

或者你想要一个列表:

 >>> name = list(iter(partial(raw_input,'Name:'),''))
名称:nosklo
名称:Andreas
名称:Aaron
名称:Phil
名称:
>>>名字
['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天全站免登陆