random.sample
时间: 2023-10-14 20:24:22 浏览: 67
The random.sample() function in Python is a method that returns a unique random sample of elements from a given sequence (list, tuple, set, etc.) without replacement. The function takes two arguments - the sequence and the size of the sample. The size of the sample must be less than or equal to the length of the sequence.
For example, if we have a list of numbers from 1 to 10, we can use random.sample() to get a random sample of 3 numbers:
```
import random
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sample = random.sample(numbers, 3)
print(sample)
```
Output:
```
[8, 2, 7]
```
In this example, we get a random sample of 3 elements from the list of numbers, which are 8, 2, and 7. The order of the elements is also random.
Note that if we try to get a sample size larger than the length of the sequence, an error will occur.
阅读全文