我想將下面的代碼轉換為串列理解。
for i in list:
if i>b:
i=5
else:
i=0
我嘗試使用[i if i>b 5 else 0 for i in a],但導致語法錯誤。我也嘗試過[i for i in a if i>b 5 else 0],但這也導致了語法錯誤。
有什么解決辦法嗎?
uj5u.com熱心網友回復:
您的嘗試:
[i if i>b 5 else 0 for i in a]
很接近,你只想給5不i喜歡這樣:
[5 if i>b else 0 for i in a]
測驗代碼:
a = [1,2,3,4,5,6,7,8,9,10]
b = 3
output = [5 if i>b else 0 for i in a]
print(output)
輸出:
[0, 0, 0, 5, 5, 5, 5, 5, 5, 5]
這是有效的,因為在if陳述句評估為時給出了之前的專案,否則給出True了之后的值。else所以:
output = NumberIfTrue if LogicStatement else NumberIfFalse
相當于:
if LogicStatement:
output = NumberIfTrue
else:
output = NumberIfFalse
在你的情況下:
LogicStatement = i>b
NumberIfTrue = 5
NumberIfFalse = 0
因此您需要(如上所示):
5 if i>b else 0
然后,您想將此應用于串列中的每個專案,其中添加:
for i in a
像這樣:
5 if i>b else 0 for i in a
現在這是一個生成器,因為您需要一個串列,所以您必須用[]括號括住生成器,以便它“生成”具有您想要的值的串列。所以就:
[5 if i>b else 0 for i in a]
然后為了得到最終的解決方案,我們只需將結果分配給output以便可以再次使用它:
output = [5 if i>b else 0 for i in a]
uj5u.com熱心網友回復:
在你的版本中
[i if i>b 5 else 0 for i in list]
語法錯誤就在 i>b 之后。你在那里有“真正的價值”,它在錯誤的地方。重復你的原始代碼
for i in list:
if i>b: #condition
i=5 #true action
else:
i=0 #false action
真正的答案是
[5 if i > b else 0 for i in list]
偽代碼版本
[<true action> if <condition> else <false action> for i in list]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427432.html
標籤:Python python-3.x 列表 列表理解
