pychon 输入20个整数 统计每个整数出现的次数
时间: 2023-12-20 18:06:45 浏览: 35
可以使用Python中的字典(dictionary)来记录每个整数出现的次数,具体实现如下:
```python
num_list = input("请输入20个整数,以空格分隔:").split()
num_dict = {}
for num in num_list:
if num in num_dict:
num_dict[num] += 1
else:
num_dict[num] = 1
for num, count in num_dict.items():
print(f"{num}: {count}次")
```
首先通过`input()`函数获取用户输入的20个整数,然后使用`split()`方法将字符串按照空格分隔成列表。接着,定义一个空字典`num_dict`用于记录每个整数出现的次数。使用`for`循环遍历列表中的每个整数,如果该整数已经在字典中出现过,则将其对应的值加1,否则在字典中新增一对键值对,键为该整数,值为1。最后,使用`items()`方法遍历字典中的每一对键值对,打印出每个整数及其出现次数。
相关问题
统计每个整数出现次数用python代码表示
好的,你可以使用 Python 中的字典数据结构来实现统计每个整数出现的次数。以下是一个示例代码:
```python
# 定义一个整数数组
nums = [1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1]
# 定义一个空字典,用于保存每个整数出现的次数
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("整数 " + str(num) + " 出现了 " + str(count) + " 次。")
```
这段代码会输出以下结果:
```
整数 1 出现了 4 次。
整数 2 出现了 3 次。
整数 3 出现了 2 次。
整数 4 出现了 1 次。
整数 5 出现了 1 次。
```
Python问题:输入若干个整数,统计出现次数最多的那个
可以使用字典来统计每个数字出现的次数,然后找出出现次数最多的那个数字。以下是一个示例代码:
```python
nums = input("请输入若干个整数,用空格分隔:").split()
count_dict = {}
for num in nums:
if num in count_dict:
count_dict[num] += 1
else:
count_dict[num] = 1
max_count = 0
max_num = None
for num, count in count_dict.items():
if count > max_count:
max_count = count
max_num = num
print("出现次数最多的数字是:", max_num)
```
首先,通过 `input` 函数获取用户输入的若干个整数,并使用 `split` 方法将其转换为一个列表 `nums`。
接下来,定义一个空字典 `count_dict`,用于统计每个数字出现的次数。遍历 `nums` 列表中的每个数字,如果该数字已经在字典中出现过,则将其出现次数加 1,否则将其出现次数初始化为 1。
然后,遍历 `count_dict` 字典中的每个键值对,找出出现次数最多的那个数字,并将其保存在 `max_num` 变量中。
最后,输出出现次数最多的数字。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)