我已經使用傳統方法解決了以下代碼:
edades = [10, 25, 49, 16, 60]
mayores_edad = []
for edad in edades:
if edad >= 18:
mayores_edad.append(1)
else:
mayores_edad.append(0)
print("Mayores de edad:", mayores_edad)
現在我想做同樣的事情,但使用列表理解。我已經做到了:
mayores_edad_por_compresion = [x if (x >= 18) == 1 else 0 for x in edades]
print(mayores_edad_por_compresion)
問題是,結果是這樣的:[10, 0, 0, 16, 0]
,我需要它像傳統的[0, 1, 1, 0, 1]
一樣。
我做錯了什么?提前謝謝。
簡單地說,當條件為true時,您希望列表中的值為
1
,而不是x
,因此您應該編寫相反請注意,比較
==1
是不必要的,應該刪除。此外,在這種特殊情況下,您可以將條件轉換為整數。
這是否比另一種方法更好/更清楚是opinion-based,但最好知道這種替代方法。