Python编写程序,生成包含1000个0~100之间的随机整数,并统计每个元素的出现次数
时间: 2024-03-12 16:48:17 浏览: 211
好的,这是一个简单的程序,可以使用 Python 的 random 模块来生成随机数,使用字典来统计出现次数。以下是示例代码:
```python
import random
# 生成1000个随机整数
nums = [random.randint(0, 100) for _ in range(1000)]
# 统计每个元素的出现次数
count = {}
for num in nums:
if num in count:
count[num] += 1
else:
count[num] = 1
# 输出结果
for num, c in count.items():
print(f"{num}: {c}")
```
这段代码首先使用列表推导式生成1000个随机整数,然后使用字典来统计每个元素的出现次数。最后遍历字典输出结果。
相关问题
编写python程序,生成包含1000个0~100的随机整数,并统计每个元素出现的次数
可以使用random模块生成随机整数,使用字典来记录每个元素出现的次数。
下面是一个示例代码:
```python
import random
# 生成1000个随机整数
nums = [random.randint(0, 100) for _ in range(1000)]
# 统计每个元素出现的次数
counts = {}
for num in nums:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
# 输出结果
for num, count in counts.items():
print(f"{num}: {count}")
```
输出结果类似于:
```
0: 12
1: 9
2: 14
3: 11
4: 11
5: 9
6: 10
7: 6
8: 7
9: 13
...
```
编写Python程序,生成包含1000个0~100的随机整数,并统计每个元素的出现次数。
好的,以下是实现该功能的Python程序:
```python
import random
# 生成1000个0~100的随机整数
lst = [random.randint(0, 100) for i in range(1000)]
# 统计每个元素的出现次数
freq = {}
for num in lst:
freq[num] = freq.get(num, 0) + 1
# 输出结果
for i in range(101):
if i in freq:
print("{}: {}".format(i, freq[i]))
else:
print("{}: 0".format(i))
```
该程序使用了Python内置的random库来生成1000个0~100之间的随机整数。然后使用一个字典来统计每个元素出现的次数,最终输出结果。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![](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)