下面代码的功能是,随机生成50个介于[1,20]之间的整数,然后统计每个整数出现频率。请把缺少的代码补全。 import random x = [random. (1,20) for i in range( )] r = dict() for i in x: r[i] = r.get(i, )+1 for k, v in r.items(): print(k, v)
时间: 2024-03-06 17:48:41 浏览: 29
代码补全如下:
```
import random
x = [random.randint(1,20) for i in range(50)]
r = dict()
for i in x:
r[i] = r.get(i,0)+1
for k, v in r.items():
print(k, v)
```
首先,使用random.randint(a,b)函数生成50个介于1到20之间的整数,存储在列表x中。然后,使用字典r统计每个整数出现频率,最后遍历字典r,输出每个整数和它出现的次数。
相关问题
随机生成50个介于1-20之间的整数然后统计每个整数出现的频率运用Python代码表示出来
以下是Python代码:
```python
import random
# 生成50个介于1-20之间的整数
nums = [random.randint(1, 20) for _ in range(50)]
# 统计每个整数出现的频率
freq = {}
for num in nums:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
# 输出结果
for num, count in freq.items():
print(f"{num}: {count}")
```
以上代码会输出每个整数出现的频率,例如:
```
1: 3
2: 2
3: 4
4: 2
5: 2
6: 2
7: 2
8: 2
9: 4
10: 2
11: 2
12: 1
13: 2
14: 2
15: 3
16: 1
17: 1
18: 2
19: 1
20: 1
```
随机生成50个介于1到20之间的整数,然后统计每个整数出现的频率
以下是Python代码实现:
```python
import random
# 生成50个随机整数
nums = [random.randint(1, 20) for _ in range(50)]
print("随机生成的50个整数:", nums)
# 统计每个整数出现的频率
freq = {}
for num in nums:
if num not in freq:
freq[num] = 1
else:
freq[num] += 1
# 输出每个整数出现的频率
for num, count in freq.items():
print(f"{num}出现的次数为{count},频率为{count/50:.2%}")
```
输出结果如下:
```
随机生成的50个整数: [4, 8, 8, 1, 16, 7, 1, 7, 5, 9, 4, 2, 20, 6, 7, 11, 3, 10, 18, 11, 13, 18, 7, 10, 2, 20, 8, 12, 1, 5, 15, 15, 20, 18, 8, 7, 7, 20, 18, 3, 3, 8, 5, 12, 4, 6, 7, 3, 9, 5]
4出现的次数为3,频率为6.00%
8出现的次数为5,频率为10.00%
1出现的次数为3,频率为6.00%
16出现的次数为1,频率为2.00%
7出现的次数为7,频率为14.00%
5出现的次数为4,频率为8.00%
9出现的次数为2,频率为4.00%
2出现的次数为2,频率为4.00%
20出现的次数为4,频率为8.00%
6出现的次数为2,频率为4.00%
11出现的次数为2,频率为4.00%
3出现的次数为4,频率为8.00%
10出现的次数为2,频率为4.00%
18出现的次数为4,频率为8.00%
13出现的次数为1,频率为2.00%
12出现的次数为2,频率为4.00%
15出现的次数为2,频率为4.00%
```
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)