use of random.choices
时间: 2023-10-23 10:21:06 浏览: 84
随机数的使用
The `random.choices` method is used to randomly select elements from a given sequence with replacement. It takes two arguments - the sequence to choose from and the number of elements to choose.
For example, let's say we have a list of fruits `fruits = ['apple', 'banana', 'orange', 'kiwi', 'mango']` and we want to randomly select 3 fruits from this list. We can use `random.choices` as follows:
```
import random
fruits = ['apple', 'banana', 'orange', 'kiwi', 'mango']
selected_fruits = random.choices(fruits, k=3)
print(selected_fruits)
```
Output:
```
['kiwi', 'kiwi', 'banana']
```
Note that since `random.choices` selects elements with replacement, it is possible to get the same element multiple times in the output.
阅读全文