随机生成1000个1到10之间的整数,使用字典统计每个数出现的次数。python
时间: 2024-05-11 19:19:15 浏览: 6
可以使用Python中的字典(dictionary)来统计每个数出现的次数,具体代码如下:
```python
import random
# 生成1000个1到10之间的随机整数
numbers = [random.randint(1, 10) for _ in range(1000)]
# 使用字典统计每个数出现的次数
counts = {}
for num in numbers:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
# 输出每个数出现的次数
for num, count in counts.items():
print(f"{num}: {count}")
```
这里使用了Python中的列表推导式(list comprehension)和字典的items()方法,可以让代码更简洁。
相关问题
随机生成1000个1~10之间的整数,使用字典统计每个数的出现次数
可以使用Python中的字典来实现统计每个数的出现次数。具体方法如下:
```python
import random
# 生成1000个1~10之间的随机整数
nums = [random.randint(1, 10) for _ in range(1000)]
# 使用字典统计每个数的出现次数
count_dict = {}
for num in nums:
if num in count_dict:
count_dict[num] += 1
else:
count_dict[num] = 1
# 输出每个数的出现次数
for num, count in count_dict.items():
print("{}出现了{}次".format(num, count))
```
运行结果如下:
```
1出现了89次
2出现了97次
3出现了96次
4出现了97次
5出现了107次
6出现了91次
7出现了109次
8出现了98次
9出现了113次
10出现了103次
```
随机生成1000个1-10之间的整数,使用字典统计每个数的出现次数
可以使用Python语言中的字典来实现统计每个数的出现次数。下面是实现的代码:
```python
import random
# 生成1000个1-10之间的随机整数
nums = [random.randint(1, 10) for _ in range(1000)]
# 使用字典统计每个数的出现次数
count = {}
for num in nums:
if num not in count:
count[num] = 1
else:
count[num] += 1
# 输出结果
for num in count:
print(f"{num}: {count[num]}")
```
输出结果类似于:
```
1: 93
2: 107
3: 95
4: 89
5: 101
6: 100
7: 100
8: 98
9: 106
10: 111
```