Python random
时间: 2023-11-05 17:12:36 浏览: 79
python-random
Python random module provides a suite of functions to generate random numbers and values. Here are some commonly used functions:
1. random(): Returns a random floating-point number in the range [0.0, 1.0).
2. randint(a, b): Returns a random integer between a and b (inclusive).
3. uniform(a, b): Returns a random floating-point number between a and b.
4. choice(seq): Returns a random element from the given sequence.
5. shuffle(seq): Shuffles the elements in the given sequence randomly.
6. sample(seq, k): Returns k random elements from the given sequence without replacement.
Example:
```
import random
# Generate a random number between 0 and 1
print(random.random())
# Generate a random integer between 1 and 10
print(random.randint(1, 10))
# Generate a random floating-point number between 0 and 1
print(random.uniform(0, 1))
# Choose a random element from the given sequence
print(random.choice(['apple', 'banana', 'cherry']))
# Shuffle the elements in the given sequence
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)
# Sample 3 random elements from the given sequence without replacement
my_list = [1, 2, 3, 4, 5]
print(random.sample(my_list, 3))
```
阅读全文