###### tags: `Python`,`TQC` # TQC+ 程式語言Python 807 字串加總 1. 題目說明: 請開啟PYD807.py檔案,依下列題意進行作答,計算數字加總並計算平均,使輸出值符合題意要求。作答完成請另存新檔為PYA807.py再進行評分。 2. 設計說明: 請撰寫一程式,要求使用者輸入一字串,該字串為五個數字,以空白隔開。請將此五個數字加總(Total)並計算平均(Average)。 3. 輸入輸出: 輸入說明 一個字串(五個數字,以空白隔開) 輸出說明 總合 平均 (輸出浮點數到小數點後第一位) ![](https://i.imgur.com/kZqq90D.png) ```python= #method 1 num = input() n1 = num.split(" ") #<class 'list'> n2 = [int(i) for i in n1] #list comprehension print("Total = {}".format(sum(n2))) print("Average = {:.1f}".format(sum(n2)/len(n2))) #method 2 a = input() a1 = a.split(" ") #<class 'list'> tot = 0 for i in a1: tot = tot + int(i) print("Total = {}".format(tot)) print("Average = {:.1f}".format(tot/len(a1))) ``` ```python= # List Comprehension # List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [] for x in fruits: if "a" in x: newlist.append(x) print(newlist) #['apple', 'banana', 'mango'] fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if "a" in x] print(newlist) #['apple', 'banana', 'mango'] ```