Python编写程序产生10个1~100的随机数,使用列表存放并输出。
时间: 2024-03-20 21:42:39 浏览: 35
好的,以下是Python程序的代码实现:
```python
import random
# 生成随机数
random_list = []
for i in range(10):
random_list.append(random.randint(1, 100))
# 输出随机数列表
print(random_list)
```
程序首先导入了Python内置的 `random` 模块,然后使用 `for` 循环生成10个1~100的随机数,并将它们添加到一个列表中。最后,程序输出了这个随机数列表。
相关问题
Python编写程序产生10个1~100的随机数,使用列表存放并输出。最后将不能被二整除的列表值输出。
好的,以下是Python程序的代码实现:
```python
import random
# 生成随机数
random_list = []
for i in range(10):
random_list.append(random.randint(1, 100))
# 输出随机数列表
print("随机数列表:", random_list)
# 输出不被2整除的随机数列表
result_list = []
for num in random_list:
if num % 2 != 0:
result_list.append(num)
print("不能被2整除的随机数列表:", result_list)
```
程序首先与上一个问题一样生成10个1~100的随机数,并将它们添加到一个列表中。接着,程序使用 `for` 循环遍历随机数列表,将不能被2整除的随机数添加到一个新的列表 `result_list` 中。最后,程序输出原始随机数列表与不被2整除的随机数列表。
编写程序统计50个1~30的随机数中每个随机数出现了多少次。要求: 统计用字典进行 随机数存放在列表中 输出结果是要求按照随机数由大到小的顺序输出
以下是Python的代码实现:
```python
import random
# 生成50个1~30的随机数
lst = [random.randint(1, 30) for _ in range(50)]
# 使用字典统计每个随机数出现的次数
count_dict = {}
for num in lst:
count_dict[num] = count_dict.get(num, 0) + 1
# 按照随机数由大到小的顺序输出结果
for num, count in sorted(count_dict.items(), reverse=True):
print(f"{num}: {count}")
```
运行结果类似于:
```
30: 3
29: 1
28: 2
27: 1
26: 1
25: 2
24: 1
23: 1
22: 1
21: 1
20: 1
19: 1
18: 2
17: 2
16: 1
15: 1
14: 1
13: 1
12: 1
11: 1
10: 1
9: 1
8: 1
7: 1
6: 1
5: 2
4: 1
3: 1
2: 1
1: 1
```