编写程序统计50个1~30的随机数中每个随机数出现了多少次。要求: 统计用字典进行 随机数存放在列表中 输出结果是要求按照随机数由大到小的顺序输出
时间: 2023-06-18 19:07:05 浏览: 64
以下是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
```
相关问题
编写程序,生成一个列表,包含25个60-79之间的随机数,并统计列表中有几个不一样的数字及其出现的次数
你可以使用Python内置的random模块来生成随机数。以下是一个可能的实现:
```python
import random
random_list = [random.randint(60, 79) for _ in range(25)]
print("随机数列表:", random_list)
unique_nums = set(random_list)
num_count = {num: random_list.count(num) for num in unique_nums}
print("不同数字数量:", len(unique_nums))
print("每个数字出现的次数:", num_count)
```
首先,我们使用列表推导式生成一个包含25个60-79之间随机数的列表。然后,我们使用set函数获取列表中不同的数字,并使用字典推导式统计每个数字在列表中出现的次数。
输出结果类似如下:
```
随机数列表: [75, 69, 67, 65, 66, 60, 71, 72, 75, 65, 71, 72, 78, 66, 68, 72, 63, 67, 71, 62, 76, 71, 69, 78, 73]
不同数字数量: 15
每个数字出现的次数: {65: 2, 66: 2, 67: 2, 68: 1, 69: 2, 71: 4, 72: 4, 73: 1, 75: 2, 76: 1, 78: 2, 60: 1, 62: 1, 63: 1}
```
输出结果中,不同数字数量为15,即列表中有15个不同的数字;每个数字出现的次数也被正确地统计出来。
python中编写一个函数,随机产生n个[start,end]范围内的随机数,统计每个元素出现的次数。要求:n,start,end都为参数
以下是实现您要求的Python函数,该函数可以随机生成n个[start,end]范围内的随机数,并统计每个元素出现的次数:
```python
import random
def count_random_numbers(n, start, end):
a = [random.randint(start, end) for _ in range(n)]
counts = {i: a.count(i) for i in set(a)}
return counts
```
函数中,我们使用了Python的random模块来生成随机数,其中randint()函数可以生成指定范围内的随机整数。我们使用列表生成式生成n个[start,end]范围内的随机整数,并使用字典推导式统计每个元素出现的次数。最后,我们将结果以字典的形式返回。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)