简体   繁体   English

在 python def 语句中,是否可以在一行中编写 for 循环和 return 语句?

[英]In python def statement, Is it possible to write the for loop and return statements in one line?

# code 1
def x():
    for i in range(3):
        print(i)
    return None

# code 2
def x():
    for i in range(3): print(i); return None

# code 3
def x():
    for i in range(3):
        print(i)
        return None

# code 4
def x():
    for i in range(3): print(i)
    return None

Hello.你好。 I was testing about one line statements in Python.我正在测试 Python 中的一行语句。 PEP 8 doesn't recommend this, but I wonder if it's possible. PEP 8 不建议这样做,但我想知道这是否可能。

I initially tried to write code 1 in one line like code 2. However, I found that the function ended in the first loop and realized that code 2 was the same as code 3. And I've reached the code 4.我最初尝试将代码 1 像代码 2 一样写在一行中。但是,我发现 function 在第一个循环中结束,并意识到代码 2 与代码 3 相同。我已经到达了代码 4。

However, I wonder if it's possible to abbreviate code 4 more and write it in one line.但是,我想知道是否可以将代码 4 缩写并写在一行中。


Thank you for answering.谢谢你的回答。 That's right.这是正确的。 The return None is virtually meaningless because it can be omitted. return None实际上是没有意义的,因为它可以被省略。 I needed to write the questions more carefully.我需要更仔细地写问题。 But what if you want to return a processed value other than None as below?但是,如果您想返回None以外的处理值,如下所示怎么办? I abbreviated code 1 to code 2.我将代码 1 缩写为代码 2。

# code 1
def x():
    processed_values = []
    for i in range(3):
        processed_values.append(i*2)
    return processed_values
print(x())

# code 2
def y():
    processed_values = []
    for i in range(3): processed_values.append(i*2)
    return processed_values
print(y())

Firstly, you don't need to specifically call return None as this is done automatically.首先,您不需要专门调用return None因为这是自动完成的。 This saves us one line by default.这默认为我们节省了一行。 Secondly, you can create lambda functions which are one-liner functions.其次,您可以创建 lambda 函数,它们是单行函数。

x = lambda num: [print(i) for i in range(num)]

# then calling your new function as normal
x(3)

This is functionally equivalent to:这在功能上等同于:

def x(num):
    [print(i) for i in range(num)]

You can do this using list comprehension.您可以使用列表推导来做到这一点。

def code5():
    [print(i) for i in range(3)]; return None

The return statement here does not do anything much.这里的 return 语句没有做太多的事情。 So you can totally avoid it.所以你完全可以避免它。

But most importantly, don't write code like this in any production application.但最重要的是,不要在任何生产应用程序中编写这样的代码。 This kind of coding is only going to make the things complicated and harder to understand.这种编码只会使事情变得复杂和难以理解。

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

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