生成1-30乱序随机不重复的数 python
时间: 2024-05-05 18:15:31 浏览: 19
以下是使用Python生成1-30乱序随机不重复的数的代码:
```python
import random
# 生成1-30的整数列表
nums = list(range(1, 31))
# 随机打乱列表
random.shuffle(nums)
# 取前30个数
result = nums[:30]
# 输出结果
print(result)
```
输出结果类似于:
```
[16, 22, 12, 21, 27, 29, 14, 7, 17, 8, 10, 6, 9, 5, 19, 26, 4, 15, 1, 23, 24, 2, 20, 28, 11, 3, 25, 13, 18, 30]
```
这段代码生成了一个包含1-30之间的乱序随机不重复的30个整数的列表。
相关问题
python随机生成不重复数字
可以使用Python的random模块生成100个随机整数,然后使用字典来统计每个数字出现的次数。具体代码如下:
```python
import random
# 生成100个随机整数
nums = [random.randint(1, 100) for _ in range(100)]
# 统计数字出现的次数
count_dict = {}
for num in nums:
if num in count_dict:
count_dict[num] += 1
else:
count_dict[num] = 1
# 输出结果
for num, count in count_dict.items():
print(f"{num}: {count}")
```
这段代码会输出每个数字出现的次数,例如:
```
1: 12
2: 8
3: 14
4: 10
5: 11
6: 12
7: 9
8: 10
9: 11
10: 13
...
```
代码生成(python 1-34随机生成7个不重复的数字)
下面是一段生成 7 个在 1 到 34 之间不重复随机数字的 Python 代码:
```
import random
def generate_random_numbers():
random_numbers = random.sample(range(1, 35), 7)
return random_numbers
print(generate_random_numbers())
```
在这段代码中,我们使用了 Python 标准库 `random` 中的 `sample` 函数来生成不重复的随机数字。