Python生成100个以上的随机数1或0,统计0和1出现的次数
时间: 2024-05-05 19:16:45 浏览: 17
可以使用random模块中的randint函数生成随机数,然后用循环生成100个随机数,并统计0和1出现的次数。代码如下:
```python
import random
# 初始化0和1的计数器
count0 = 0
count1 = 0
# 生成100个随机数并统计0和1的出现次数
for i in range(100):
num = random.randint(0, 1)
if num == 0:
count0 += 1
else:
count1 += 1
print('0的出现次数:', count0)
print('1的出现次数:', count1)
```
输出结果如下:
```
0的出现次数: 51
1的出现次数: 49
```
相关问题
生成0到100的200个随机数 并统计出现的次数
好的,我可以帮你生成200个0到100之间的随机数,并统计每个数字出现的次数。以下是Python代码的示例:
```python
import random
numbers = [random.randint(0, 100) for i in range(200)]
count = {}
for num in numbers:
if num in count:
count[num] += 1
else:
count[num] = 1
for num, freq in count.items():
print(f"{num}出现了{freq}次")
```
这段代码会生成一个包含200个0到100的随机整数的列表,然后通过遍历整个列表并使用字典来记录每个数字的出现次数。最后,它会打印出每个数字和它出现的次数。
python生成1000个0-100的整数 统计每个元素出现的次数
可以使用Python内置的random模块生成随机数,再使用collections模块中的Counter类来统计每个元素出现的次数。
代码如下:
```python
import random
from collections import Counter
# 生成1000个0-100的整数
lst = [random.randint(0, 100) for _ in range(1000)]
# 统计每个元素出现的次数
counter = Counter(lst)
# 输出结果
for i in range(101):
print(f"{i}: {counter[i]}")
```
输出结果类似如下:
```
0: 9
1: 17
2: 15
3: 13
4: 19
5: 10
6: 14
7: 12
8: 8
9: 16
10: 10
...
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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_lunwen.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)
![](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)