# 函數 ---- <iframe width="100%" height="500" src="https://hackmd.io/@ckshcsdc4th/r1Xe-w6Z6" frameborder="0"></iframe> ---- ## Python常用函數庫 ---- ## math ---- 當你使用Python的math函數庫時,可以進行各種數學計算。以下是一些math函數庫的例子 ---- ### 數值運算 ---- 平方根 ```py! import math # 平方根 sqrt_result = math.sqrt(25) print(sqrt_result) # 輸出: 5.0 ``` ---- 指數 ```py! import math # 指數 exp_result = math.exp(2) print(exp_result) # 輸出: 7.3890560989306495 ``` ---- 對數 ```py! import math # 對數 log_result = math.log(10, 2) print(log_result) # 輸出: 3.3219280948873626 ``` ---- 階乘 ```py! import math # 階乘 factorial_result = math.factorial(5) print(factorial_result) # 輸出: 120 ``` ---- ### 數學常數 ---- 圓周率 ```py! import math # 圓周率 pi_value = math.pi print(pi_value) # 輸出: 3.141592653589793 ``` ---- 自然對數的底 ```py! import math # 自然對數的底 e_value = math.e print(e_value) # 輸出: 2.718281828459045 ``` ---- ### 三角函數 ---- 正弦sin ```py! import math # 正弦 sin_result = math.sin(math.radians(30)) # 將角度轉換為弧度 print(sin_result) # 輸出: 0.49999999999999994 ``` ---- 餘弦cos ```py! import math # 餘弦 cos_result = math.cos(math.radians(60)) print(cos_result) # 輸出: 0.5000000000000001 ``` ---- 正切tan ```py! import math # 正切 tan_result = math.tan(math.radians(45)) print(tan_result) # 輸出: 0.9999999999999999 ``` ---- #### 來寫個例題吧 ---- 題:考慮一個直角三角形,其中一個銳角為30度。 假設直角邊的長度為5(對邊)。請計算以下數值: 1.斜邊的長度。 2.另一銳角的大小(以度為單位)。 3.直角三角形的面積。 ---- 解 ```py! import math # 已知數據 angle_A_deg = 30 # 第一個銳角的度數 side_a = 5 # 直角邊的長度 # 計算斜邊的長度 side_c = side_a / math.sin(math.radians(angle_A_deg)) # 計算另一銳角的大小 angle_B_deg = 90 - angle_A_deg # 計算直角三角形的面積 triangle_area = 0.5 * side_a * side_c # 輸出結果 print(f"斜邊的長度:{side_c:.2f}") print(f"另一銳角的大小:{angle_B_deg:.2f} 度") print(f"直角三角形的面積:{triangle_area:.2f}") ``` ---- 我分的夠詳細吧 :sunglasses: ---- 我來說明一下 ---- ``` 斜邊的長度:使用三角函數中的正弦函數, 斜邊長度可以通過直角邊長度和角度計算得出。 ``` ---- ``` 另一銳角的大小:由於是直角三角形,兩銳角的和為90度 因此第二個銳角的大小可以通過第一個銳角的大小計算得出。 ``` ---- ``` 直角三角形的面積:使用直角三角形的面積公式,面積等於直角邊的乘積除以2。 ``` ---- 就醬 不難對吧 :+1: --- ## random ---- 當你使用Python的random函數庫時,可以進行各種隨機數生成和相關操作。 以下是一些random函數庫的例子: ---- 生成隨機整數 ```py! import random # 生成一個範圍在1到10之間的隨機整數 random_integer = random.randint(1, 10) print(random_integer) ``` ---- 生成隨機浮點數 ```py! import random # 生成一個範圍在0到1之間的隨機浮點數 random_float = random.random() print(random_float) ``` ---- 從列表中隨機選擇元素: ```py! import random # 從列表中隨機選擇一個元素 my_list = [1, 2, 3, 4, 5] random_element = random.choice(my_list) print(random_element) ``` ---- 打亂列表的順序: ```python! import random # 打亂列表的順序 my_list = [1, 2, 3, 4, 5] random.shuffle(my_list) print(my_list) ``` ---- 生成隨機字母: ```py! import random import string # 生成一個隨機字母 random_letter = random.choice(string.ascii_letters) print(random_letter) ``` ---- 生成隨機密碼: ```py! import random import string # 生成一個8位的隨機密碼 password = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) print(password) ``` ---- 又到了快樂的練習時間:D ---- 題: 假設你在一個抽獎活動中,有10個參與者,每個參與者都有一個獎勵等級(1到5)。請完成以下任務: 1.使用random函數庫生成每個參與者的獎勵等級,並將結果儲存在一個列表中。 2.找出獎勵等級最高的參與者。 3.計算所有參與者的平均獎勵等級。 ---- 解 ```py! import random # 生成每個參與者的獎勵等級 participants_rewards = [random.randint(1, 5) for _ in range(10)] # 找出獎勵等級最高的參與者 max_reward = max(participants_rewards) max_reward_index = participants_rewards.index(max_reward) + 1 # +1 是因為列表的索引從0開始 # 計算所有參與者的平均獎勵等級 average_reward = sum(participants_rewards) / len(participants_rewards) # 輸出結果 print(f"每個參與者的獎勵等級:{participants_rewards}") print(f"獎勵等級最高的參與者是第 {max_reward_index} 號,獎勵等級為 {max_reward}") print(f"所有參與者的平均獎勵等級為 {average_reward:.2f}") ``` ---- 說明 ---- ``` 生成每個參與者的獎勵等級:使用列表推導式和 random.randint生成包含10個元素的列表 每個元素都是1到5之間的隨機整數,代表每個參與者的獎勵等級。 ``` ---- ``` 找出獎勵等級最高的參與者:使用max函數找到列表中的最大值 然後使用index方法找到該最大值的索引,再加上1得到參與者的編號。 ``` ---- ``` 計算所有參與者的平均獎勵等級: 使用sum函數計算所有獎勵等級的總和,除以參與者的數量得到平均值。 ``` ---- 還行對吧 :accept: --- ## datetime ---- 使用 Python 的 datetime 函數庫,你可以輕鬆處理日期和時間。以下是一些 datetime 函數庫的例子: ---- 獲取當前日期和時間: ```py! from datetime import datetime # 獲取當前日期和時間 current_datetime = datetime.now() print(current_datetime) ``` ---- 格式化日期和時間: ```py! from datetime import datetime # 格式化日期和時間 formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S") print(formatted_datetime) ``` ---- 解析字符串為日期和時間對象: ```py! from datetime import datetime # 解析字符串為日期和時間對象 date_string = "2023-01-15" parsed_date = datetime.strptime(date_string, "%Y-%m-%d") print(parsed_date) ``` ---- 計算日期差: ```py! from datetime import datetime, timedelta # 計算日期差 future_date = current_datetime + timedelta(days=7) date_difference = future_date - current_datetime print(f"未來日期:{future_date}, 差距:{date_difference}") ``` ---- 計算時間差: ```py! from datetime import datetime, timedelta # 計算時間差 future_time = current_datetime + timedelta(hours=3) time_difference = future_time - current_datetime print(f"未來時間:{future_time}, 差距:{time_difference}") ``` ---- 又是快樂的解題時間 :smiling_imp: ---- 問題: 假設今天是2023年1月15日,你正在計劃一個項目,該項目需要在未來的某個日期完成。 請完成以下任務: 1.使用 datetime 函數庫計算並輸出項目的截止日期,該截止日期為從今天開始的30天後。 2.設定一個提醒時間,在項目截止日期的前一天下午3點提醒。 ---- 解 ---- ```py! from datetime import datetime, timedelta # 今天的日期 today = datetime(2023, 1, 15) # 計算項目的截止日期(30天後) deadline = today + timedelta(days=30) # 提醒時間(截止日期的前一天下午3點) reminder_time = deadline - timedelta(days=1, hours=9) # 下午3點是9小時後 # 輸出結果 print(f"項目的截止日期為:{deadline.strftime('%Y-%m-%d')}") print(f"提醒時間設定為:{reminder_time.strftime('%Y-%m-%d %H:%M:%S')}") ``` ---- ``` 計算項目的截止日期:使用 datetime 函數創建今天的日期 然後使用 timedelta 計算 30 天後的日期。 ``` ---- ``` 設定提醒時間:計算截止日期的前一天,下午3點是9小時後 因此減去 timedelta(days=1, hours=9)。 ``` --- ## os ---- 使用 Python 的 os 函數庫,你可以進行與操作系統相關的操作,例如檔案和目錄的管理、執行系統命令等。以下是一些 os 函數庫的例子: ---- 列出目錄中的檔案和子目錄: ```py! import os # 獲取當前目錄下的檔案和子目錄列表 current_dir = os.getcwd() files_and_dirs = os.listdir(current_dir) print(files_and_dirs) ``` ---- 創建目錄: ```py! import os # 創建一個名為 "new_directory" 的目錄 new_directory_path = os.path.join(os.getcwd(), "new_directory") os.makedirs(new_directory_path) ``` ---- 刪除檔案: ```py! import os # 刪除名為 "example.txt" 的檔案 file_to_delete = os.path.join(os.getcwd(), "example.txt") os.remove(file_to_delete) ``` ---- 刪除目錄: ```py! import os # 刪除名為 "old_directory" 的目錄(必須確保目錄是空的) directory_to_delete = os.path.join(os.getcwd(), "old_directory") os.rmdir(directory_to_delete) ``` ---- 執行系統命令: ```py! import os # 使用 os.system 執行系統命令 os.system("dir") # 在 Windows 中列出當前目錄下的檔案和子目錄 ``` ---- 檢查檔案或目錄是否存在: ```py! import os # 檢查檔案是否存在 file_path = os.path.join(os.getcwd(), "example.txt") if os.path.exists(file_path): print(f"{file_path} 存在") else: print(f"{file_path} 不存在") ``` ---- 「暫時」的最後一題了 :sweat_smile: ---- 問題: 假設你正在編寫一個程序,要求使用者輸入一個目錄的路徑,然後執行以下任務: 1.列出該目錄中的所有檔案和子目錄。 2.創建一個新的子目錄,名稱為 "backup"。 3.將目錄中的所有檔案複製到 "backup" 子目錄中。 請使用 os 函數庫完成上述任務。 ---- 解 ```py! import os import shutil # 使用者輸入目錄路徑 input_directory = input("請輸入目錄路徑:") # 1. 列出目錄中的所有檔案和子目錄 files_and_dirs = os.listdir(input_directory) print(f"目錄中的檔案和子目錄:{files_and_dirs}") # 2. 創建一個新的子目錄 "backup" backup_directory = os.path.join(input_directory, "backup") os.makedirs(backup_directory) print(f"已創建新的子目錄:{backup_directory}") # 3. 將目錄中的所有檔案複製到 "backup" 子目錄中 for item in files_and_dirs: item_path = os.path.join(input_directory, item) backup_path = os.path.join(backup_directory, item) if os.path.isfile(item_path): # 如果是檔案,則複製到 "backup" 子目錄 shutil.copy2(item_path, backup_path) elif os.path.isdir(item_path): # 如果是目錄,則遞歸複製所有檔案和子目錄 shutil.copytree(item_path, backup_path) print("檔案已成功複製到 'backup' 子目錄中。") ``` ---- 說明 ---- ``` 列出目錄中的所有檔案和子目錄: 使用 os.listdir 函數獲取目錄中的所有檔案和子目錄列表。 ``` ---- ``` 創建新的子目錄 "backup": 使用 os.makedirs 函數創建一個新的子目錄 "backup"。 ``` ---- ``` 將目錄中的所有檔案複製到 "backup" 子目錄中: 使用 shutil 函數庫中的 copy2 函數複製檔案, 並使用 copytree 函數遞歸複製目錄中的所有檔案和子目錄。 最後,輸出複製成功的提示消息。 ``` --- # 容器 ---- ## 容器是什麼? ---- ## List(列表) ---- ```python # 創建一個列表包含不同類型的元素 my_list = [1, 'apple', True, 3.14, [5, 6, 7]] # 存取列表元素 print(my_list[1]) # 輸出: 'apple' # 修改列表元素 my_list[0] = 10 print(my_list) # 輸出: [10, 'apple', True, 3.14, [5, 6, 7]] ``` ---- ### 練習 假設有一個列表 my_list = [3, 6, 9, 12, 15],請寫下程式碼實現以下操作: 取得列表中的第三個元素。 將列表最後一個元素更改為 18。 在列表的末尾添加元素 21。 刪除 9 這個元素 利用切片操作取出列表中的偶數位置元素。(my_list[初:末:公差]) ---- ```python my_list = [3, 6, 9, 12, 15] print(my_list[2]) my_list[-1]=18 my_list.append(21) my_list.remove(9) print(my_list[1::2]) print(my_list) ``` ---- ## Tuple(元組) ---- ```python # 創建一個元組包含數字和字串 my_tuple = (1, 'banana', 3.14, False) # 存取元組元素 print(my_tuple[2]) # 輸出: 3.14 # 元組是不可變的,無法修改元素 # my_tuple[0] = 5 # 這會引發錯誤:TypeError: 'tuple' object does not support item assignment ``` ---- ## Dictionary(字典) ---- ```python # 創建一個字典儲存人員資訊 person = {'name': 'Alice', 'age': 30, 'job': 'Engineer'} # 存取字典元素 print(person['age']) # 輸出: 30 # 添加新的字典元素 person['city'] = 'New York' print(person) # 輸出: {'name': 'Alice', 'age': 30, 'job': 'Engineer', 'city': 'New York'} ``` ---- ### 練習 創建一個字典 car = {'brand': 'Toyota', 'model': 'Corolla', 'year': 2022},完成以下操作: 添加一個新的鍵值對,將汽車的顏色設置為 'blue'。 刪除字典中的 'year' 鍵值對。 修改 'model' 的值為 'Camry'。 取得 'brand' 的值。 ---- ```python car = {'brand': 'Toyota', 'model': 'Corolla', 'year': 2022} car['color']= 'blue' del car['year'] car['model']='Camry' print(car['brand']) ``` ---- ## Set(集合) ---- ```python # 創建兩個集合 set1 = {1, 2, 3, 4, 5} set2 = {3, 4, 5, 6, 7} # 集合操作:交集、聯集、差集 print(set1.intersection(set2)) # 輸出: {3, 4, 5} (交集) print(set1.union(set2)) # 輸出: {1, 2, 3, 4, 5, 6, 7} (聯集) print(set1.difference(set2)) # 輸出: {1, 2} (差集) ``` ---- ### 練習 創建兩個集合 set1 = {1, 2, 3, 4, 5} 和 set2 = {4, 5, 6, 7, 8},寫下程式碼實現以下操作: 求這兩個集合的交集。 求這兩個集合的聯集。 從 set1 中刪除與 set2 中重疊的元素。(set1.difference_update()) 向 set2 中添加一個新元素 9。(set2.add()) ---- ```python set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} print(set1.intersection(set2)) print(set1.union(set2)) set1.difference_update(set2) set2.add(9) print(set1,set2) ``` ---- 總整理: | | List | Tuple | Dictionary | Set | | -------- | ---- | ----- | ---------- |:------------ | | 有無順序 | 有 | 有 | 無 | 無 | | 可否更改 | 可以 | 不行 | key無法 | 可以 | | 備註 | | | key=value | 元素具唯一性 |
{"description":"I. Python容器A. List(列表)","contributors":"[{\"id\":\"3963913a-1955-4863-b231-e15edfb3078e\",\"add\":3610,\"del\":973},{\"id\":\"35a0644c-29d6-4dd3-98eb-9df68421a475\",\"add\":7648,\"del\":167}]","title":"數學"}
    222 views
   Owned this note