[英]Is it possible to write multiple statements in one line that includes a for loop and if-else statements
[英]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
你好。 我正在測試 Python 中的一行語句。 PEP 8 不建議這樣做,但我想知道這是否可能。
我最初嘗試將代碼 1 像代碼 2 一樣寫在一行中。但是,我發現 function 在第一個循環中結束,並意識到代碼 2 與代碼 3 相同。我已經到達了代碼 4。
但是,我想知道是否可以將代碼 4 縮寫並寫在一行中。
謝謝你的回答。 這是正確的。 return None
實際上是沒有意義的,因為它可以被省略。 我需要更仔細地寫問題。 但是,如果您想返回None
以外的處理值,如下所示怎么辦? 我將代碼 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())
首先,您不需要專門調用return None
因為這是自動完成的。 這默認為我們節省了一行。 其次,您可以創建 lambda 函數,它們是單行函數。
x = lambda num: [print(i) for i in range(num)]
# then calling your new function as normal
x(3)
這在功能上等同於:
def x(num):
[print(i) for i in range(num)]
您可以使用列表推導來做到這一點。
def code5():
[print(i) for i in range(3)]; return None
這里的 return 語句沒有做太多的事情。 所以你完全可以避免它。
但最重要的是,不要在任何生產應用程序中編寫這樣的代碼。 這種編碼只會使事情變得復雜和難以理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.