use of random.choices
时间: 2023-10-23 21:21:06 浏览: 35
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.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)