在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.DataFrame()處理雙維度資料,dict跟2D list轉為DataFrame有何差別?如何用index及columns屬性客製化index跟欄位名稱?df.index = [“一”,”二”,”三”,”四”] ; df.columns = 使用.head(n) ; .tail(m) ;取首n列,尾m列; .at[index,欄位名稱] 取單一資料 ; .iat[index,欄位順序] 取單一資料 ; .loc[index,欄位名稱] 取資料 ; .iloc[index,欄位順序];df.iloc[ [0,1],[0,2]])取資料 ; df.iloc[ 0:3,0:2]切片 Python: pandas.DataFrame()處理雙維度資料,dict跟2D list轉為DataFrame有何差別?如何用index及columns屬性客製化index跟欄位名稱?df.index = [“一”,”二”,”三”,”四”] ; df.columns = 使用.head(n) ; .tail(m) ;取首n列,尾m列; .at[index,欄位名稱] 取單一資料 ; .iat[index,欄位順序] 取單一資料 ; .loc[index,欄位名稱] 取資料 ; .iloc[index,欄位順序];df.iloc[ [0,1],[0,2]])取資料 ; df.iloc[ 0:3,0:2]切片](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2022/11/20221111093547_79.png?quality=90&zoom=2&ssl=1&resize=350%2C233)
![Python: 如何使用functools.reduce逐步縮減可迭代對象,合併為單個結果? import functools; product = functools.reduce( lambda x, y: x * y, numbers) ; reduce(function, sequence [, initial]) -> value ; map(function, iterable) ; filter(function, iterable) ; map ; filter Python: 如何使用functools.reduce逐步縮減可迭代對象,合併為單個結果? import functools; product = functools.reduce( lambda x, y: x * y, numbers) ; reduce(function, sequence [, initial]) -> value ; map(function, iterable) ; filter(function, iterable) ; map ; filter](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2023/06/20230626093403_49.png?quality=90&zoom=2&ssl=1&resize=350%2C233)




近期留言