Python random.choice() 方法



Python 的 random.choice() 方法用於從序列中隨機選擇一個專案。此序列可以是列表、元組、字串或其他有序元素集合。集合等其他序列不被接受為該方法的引數,並且會引發 TypeError。這是因為集合被認為是無序序列,並且不記錄其中的元素位置。因此,它們不可被索引。

在處理隨機演算法或程式時,choice() 方法非常方便。

注意 - 此函式無法直接訪問,因此我們需要匯入 random 模組,然後需要使用 random 靜態物件呼叫此函式。

語法

以下是 Python random.choice() 方法的語法:

random.choice(seq)

引數

  • seq - 這是一個有序的元素集合(例如列表、元組、字串或字典)。

返回值

此方法返回一個隨機項。

示例 1

以下示例顯示了 Python random.choice() 方法的用法。

import random #imports the random module

# Create a list, string and a tuple
lst = [1, 2, 3, 4, 5]
string = "Tutorialspoint"
tupl = (0, 9, 8, 7, 6)
dct = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

# Display the random choices from the given sequences
print("Random element in a given list", random.choice(lst))
print("Random element in a given string", random.choice(string))
print("Random element in a given tuple", random.choice(tupl))
print("Random element in a given dictionary", random.choice(dct))

執行上述程式時,會產生以下結果:

Random element in a given list 1
Random element in a given string u
Random element in a given tuple 8
Random element in a given dictionary b

如果再次執行相同的程式,結果將與第一個輸出不同:

Random element in a given list 2
Random element in a given string t
Random element in a given tuple 0
Random element in a given dictionary d

示例 2

此方法可以使用 range() 函式選擇元素範圍內的元素。

在以下示例中,透過向 range() 函式傳遞兩個整型引數來返回一個整型範圍;並將此範圍作為引數傳遞給 choice() 方法。作為返回值,我們試圖從此範圍內檢索一個隨機整數。

import random

# Pass the range() function as an argument to the choice() method
item = random.choice(range(0, 100))

# Display the random item retrieved
print("The random integer from the given range is:", item)

上述程式的輸出如下:

The random integer from the given range is: 14

示例 3

但是,如果我們建立並將其他序列物件(如集合)傳遞給 choice() 方法,則會引發 TypeError。

import random #imports the random module

# Create a set object 's'
s = {1, 2, 3, 4, 5}

# Display the item chosen from the set
print("Random element in a given set", random.choice(s))

Traceback (most recent call last):
  File "main.py", line 5, in <module>
print("Random element in a given set", random.choice(s))
  File "/usr/lib64/python3.8/random.py", line 291, in choice
return seq[i]
TypeError: 'set' object is not subscriptable

示例 4

當我們將空序列作為引數傳遞給該方法時,會引發 IndexError。

import random

# Create an empty list seq
seq = []

# Choose a random item
item = random.choice(seq)

# Display the random item retrieved
print("The random integer from the given list is:", item)

Traceback (most recent call last):
  File "main.py", line 7, in <module>
item = random.choice(seq)
  File "/usr/lib64/python3.8/random.py", line 290, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
python_modules.htm
廣告