[Python]陣列練習題

文、意如

可以挑戰看看這些題目,但請記得,先自己思考,
試著寫出程式碼。 當你真的想不出解法,或者想檢查自己的答案時,再對照解答。
1.字串列表過濾與處理

目標: 你有一份包含多個字串的列表。請寫一個程式,執行以下任務:

  1. 從列表中過濾出所有長度超過 5 個字元的字串,並將它們存入一個新的列表 long_words 中。
  2. 列印出 long_words 列表中的每一個字串,並在後面加上 ! 驚嘆號。
資料:
words = ["apple", "banana", "cat", "dog", "elephant", "fox", "grape", "hippo"]
參考解答:
words = ["apple", "banana", "cat", "dog", "elephant", "fox", "grape", "hippo"]

# 任務 1: 過濾出長度超過 5 的字串
long_words = []
for word in words:
    if len(word) > 5:
        long_words.append(word)

print("--- 長度超過 5 個字元的字串 ---")
print(long_words)

# 任務 2: 列印並加上驚嘆號
print("\n--- 加上驚嘆號的結果 ---")
for long_word in long_words:
    print(long_word + "!")
2.字串列表分析與轉換

目標: 你有一份包含多個字串的列表。請寫一個程式,執行以下任務:

  1. mixed_list  列表中的每一個字串,轉換成大寫後列印出來。
  2. 計算原始列表中所有字串的總長度。
資料:
mixed_list = ["hello", "world123", "python", "data456", "ai", "789"]
參考解答:
mixed_list = ["hello", "world123", "python", "data456", "ai", "789"]


# 任務 1: 將篩選出的字串轉換成大寫
print("\n--- 大寫後結果 ---")
for s in mixed_list :
    print(s.upper())

# 任務 2: 計算所有字串的總長度
total_length = 0
for item in mixed_list:
    total_length += len(item)

print(f"\n所有字串的總長度為:{total_length}")

 

 

Yiru@Studio - 關於我 - 意如