#Python TQC考題904 資料計算
L=[]
with open(“read.txt”,”r”,encoding=”utf-8″) as file:
for line in file:
print(line)
L.append(line.split())
#需要.split() ,不然會多\n
n=len(L)
name=[L[i][0] for i in range(n)]
h=[eval(L[i][1]) for i in range(n)]
w=[eval(L[i][2]) for i in range(n)]
h_avg=sum(h)/n
w_avg=sum(w)/n
print(“Average height: %.2f” %h_avg)
print(“Average weight: %.2f” %w_avg)
h_max=max(h)
w_max=max(w)
print(“The tallest is %s with %.2fcm” %(name[h.index(h_max)],h_max))
print(“The heaviest is %s with %.2fkg” %(name[w.index(w_max)],w_max))

“””
read.txt的內容:
Ben 175 65
Cathy 155 55
Tony 172 75
資料排列都類似
#為多了解程式結構
#多印一些list出來看:
“””


#再練習一次:

#放大程式碼:

#再練習一次:

#放大程式碼:

#放大輸出結果:

“””
#這次不用逐行讀取的方式
#使用.readlines()把所有資料都讀進來
#再想辦法處理
#其實少了題目要求的: 顯示檔案內容
前面要再多兩行
with open(“read.txt”,”r”,encoding=”utf-8″) as file:
print(file.read()) #顯示內容,題目要求
with open() as file: 需要寫兩次
#少一次,file.read()就已經讀到檔案尾部了
# data = file.readlines()會變成空list
# 或用file.seek(0)回到內容的起點處
datanew.append(data[i].replace(“\n”,””).split())
#可以看print出來的data寫,
#頭腦清晰才寫得出這一行
#其實沒有比原本逐行做容易
#程式碼:
“””

#輸出結果:

#再寫一次完整的
#包含題目要的顯示內容
#程式碼:


#輸出結果:

#老師或書上教的大同小異:

輸出結果:

“””
再多一層迴圈
for line in file:
可以不用2D list
再拆分為3個1D list
直接做好3個1D list
“””

#輸出結果:

#多餘的空白對於語法沒影響
#但可能有助於理解


![Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool_Series] 選取多個rows #bool_Series長度同rows, index也需要同df.index ,可以使用.equals() 確認: df.index.equals(mask.index) Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool_Series] 選取多個rows #bool_Series長度同rows, index也需要同df.index ,可以使用.equals() 確認: df.index.equals(mask.index)](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2025/04/20250420212553_0_6fb2c3.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

![Python: 如何使用 os.environ[“PATH”] 設定環境變數?與 sys.path.append() 差別為何? Python: 如何使用 os.environ[“PATH”] 設定環境變數?與 sys.path.append() 差別為何?](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2024/09/20240905135312_0_890fa1.png?quality=90&zoom=2&ssl=1&resize=350%2C233)
![Python: pandas.Series如何只保留str,去除重複值?#isinstance(x:Any, str) -> bool #.drop_duplicates() #Series.apply( function )逐元素應用function運算 #DataFrame.apply( function )逐Series應用function運算 .drop_duplicates() 跟.unique()有何差別? df.drop_duplicates() 等效於 df[~df.duplicated()] Python: pandas.Series如何只保留str,去除重複值?#isinstance(x:Any, str) -> bool #.drop_duplicates() #Series.apply( function )逐元素應用function運算 #DataFrame.apply( function )逐Series應用function運算 .drop_duplicates() 跟.unique()有何差別? df.drop_duplicates() 等效於 df[~df.duplicated()]](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2024/11/20241123194900_0_5218de.png?quality=90&zoom=2&ssl=1&resize=350%2C233)





近期留言