简体   繁体   English

Python:在while循环中返回多个值的优雅方式

[英]Python: Elegant way to return multiple values in a while loop

I'm pretty much just doing this... 我差不多只是这样做......

while not something():
    pass

But I want the function something() to return another value other than True or False, specifically a list. 但我希望函数something()返回除True或False以外的其他值,特别是列表。 In C I'd just return it by plugging in a reference as a parameter but Python doesn't seem to like doing things that way. 在C中我只是通过插入引用作为参数来返回它,但Python似乎不喜欢这样做。 Therefore in the something() function I would obviously just return 2 values. 因此,在something()函数中,我显然只返回2个值。 I'm ok with that. 我很好。 The issue I have is that the code with the while loop doesn't look elegant and so I presume there must be a better way. 我遇到的问题是带有while循环的代码看起来并不优雅,所以我认为必须有更好的方法。

In C: 在C:

int a[2];
while(!something(a)); //presume that 'a' updates and the loop breaks

In Python: 在Python中:

bool_value, a = something()
while not bool_value:
    bool_value, a = something()

I know it's not such a big deal but just the fact that I have to write the same line twice seems a bit bad. 我知道这不是什么大问题,但事实上我必须两次写同一行似乎有点不好。 Is there some sort of syntax I can use to call the function and return the 'a' all within the while line? 是否有某种语法可以用来调用函数并在while行中返回'a'?

while True:
    bool_value, a = something()
    if not bool_value:
       break

The answer by user2393267 is the idiomatic way of doing do..while kind of structure in Python. 通过user2393267答案是这样做的惯用方式do..while在Python这种结构。 You can, however, follow exactly the same pattern as you have in your question for the list case: 但是,您可以按照与列表案例的问题完全相同的模式:

a = [1, 2, 3]
while not something(a):
    pass

It's just not very Pythonic, but it will actually work and allow you to modify a . 这只是不是很Python的,但它的实际工作,并允许你修改a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM