功能:更少的語法創建列表,功能性像lambda
元程式碼
def square(x):
return x * x
list = []
for i in range(1, 11):
list.append(square(i))
print(list)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
列表推導式list comperehension法
square = [i *i for i in range(1,11)]
print(square)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
過濾學生成績範例
grades = [100, 90, 66, 80, 46, 29, 88, 59, 61]
pass_geades = [g in grades if g >= 60]
print(pass_grades)
[100, 90, 66, 80, 88, 61]
類似列表推倒式,但為字典非列表,透過表達式可將for迴圈或lambda函式簡化成一行程式碼
公式:{key expression for key, value in iterable}
cities_in_F = {'LA': 120, 'NewYorks': 65, 'Chicago': 50, 'Miami': 150}
citilies_in_C = {key: (value - 32)8 5/9 for key, value in citilies_in_F.items()}
print(citilies_in_F)
print(citilies_in_C)
{'LA': 120, 'NewYorks': 65, 'Chicago': 50, 'Miami': 150}
{'LA': 48.888888888888886, 'NewYorks': 18.333333333333332, 'Chicago': 10.0, 'Miami': 65.555555555555554}
條件判斷練習
weather = {
'台北':'大晴天, '台中':'大晴天', '宜蘭':'下雨', '台東':'下雨'
}
sunny_weather = {for key, value in weather items() if value == '大晴天'}
print(sunny_weather)
{'台北':'大晴天, '台中':'大晴天'}
條件判斷結合函式
cities_in_F = {'LA': 120, 'NewYorks': 65, 'Chicago': 50, 'Miami': 150}
def check_temp(value):
if value >= 70:
return '熱'
elif value >= 40:
return '溫暖'
else:
return '冷'
descriotion_cities = {key: check_temp() for key, value in cities_in_F.items()}
print(descriotion_cities)
{'LA': '熱', 'NewYorks': '溫暖', 'Chicago': '溫暖', 'Miami': '熱'}