在Python的random模組中,你可以使用sample方法來隨機選擇三個不同的號碼。這個方法允許從一個序列中隨機選擇指定數量的不重複元素。例如,如果你想從1到10之間選擇三個不同的號碼,你可以這樣做:
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 16 17:45:13 2023
@author: SavingKing
"""
import random
# 從1到10之間隨機選擇3個不同的數字
random_numbers = random.sample(range(1, 11), 3)
print(random_numbers)這段代碼首先導入random模組,然後使用sample方法從1到10的範圍中隨機選擇三個數字。由於sample方法保證選擇的元素是唯一的,所以這三個數字將是不同的。
輸出結果:

推薦hahow線上學習python: https://igrape.net/30afN
在Python中,random.shuffle 方法用於將序列中的元素隨機打亂順序。如果你想從一個數字範圍中隨機選擇三個不同的號碼,你可以首先生成一個包含這些數字的列表,然後使用 random.shuffle 將其打亂,最後選擇列表中的前三個數字。這裡有一個例子:
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 16 17:54:32 2023
@author: SavingKing
"""
import random
# 創建一個包含1到10的數字列表
numbers = list(range(1, 11))
# 使用random.shuffle隨機打亂這個列表
random.shuffle(numbers)
print("shuffle後的numbers:\n",numbers)
# 選擇打亂後列表中的前三個數字
selected_numbers = numbers[:3]
print("\n前三個數字:\n",selected_numbers)
這段代碼首先創建了一個包含1到10的數字列表,然後使用 random.shuffle 將這個列表中的元素順序隨機打亂,最後選擇打亂後列表的前三個元素。由於 random.shuffle 保證了列表中的每個元素都被隨機移動,所以選出的三個數字將是隨機且不同的。

推薦hahow線上學習python: https://igrape.net/30afN






![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://i2.wp.com/savingking.com.tw/wp-content/uploads/2024/11/20241123194900_0_5218de.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

![Python:如何使用 PyMuPDF (import fitz ) 提取 PDF 文本區塊並存儲為 DataFrame ; text: List[ Tuple[float|str|int] ] = page.get_text(“blocks”) Python:如何使用 PyMuPDF (import fitz ) 提取 PDF 文本區塊並存儲為 DataFrame ; text: List[ Tuple[float|str|int] ] = page.get_text(“blocks”)](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2025/03/20250320084417_0_7783bd.png?quality=90&zoom=2&ssl=1&resize=350%2C233)



 
																			 
																			 
																			
近期留言