開始使用免費開始

在推導式中使用條件式(2)

在前一個練習中,你在串列推導式的「謂詞運算式」部分使用了 if 條件陳述式來評估迭代變數。這個練習中,你會在串列的「輸出運算式」上使用 if-else 陳述式。

你會使用同一個串列 fellowship。請用串列推導式,並在輸出運算式中加入 if-else 條件,建立一個串列:保留 fellowship 中字元數大於等於 7 的成員,其餘成員以空字串取代。請使用 member 作為串列推導式中的迭代變數。

本練習屬於課程

Python 工具箱

檢視課程

練習說明

  • 在輸出運算式中,當字元數 >= 7 時保持字串不變,否則以空字串取代——也就是 ''""

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create a list of strings: fellowship
fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli']

# Create list comprehension: new_fellowship
new_fellowship = [____ for ____ in fellowship]

# Print the new list
print(new_fellowship)
編輯並執行程式碼