统计列表里每个数出现的次数
时间: 2023-12-20 17:04:24 浏览: 37
假设给定的列表为 `lst`,可以使用 Python 的 Counter 类来对其进行统计。
```python
from collections import Counter
lst = [1, 2, 3, 2, 1, 3, 4]
# 统计每个数出现的次数
count = Counter(lst)
# 输出统计结果
for num, freq in count.items():
print(f"{num}: {freq} times")
```
输出结果为:
```
1: 2 times
2: 2 times
3: 2 times
4: 1 times
```
相关问题
统计每个数出现的次数
根据提供的引用内容,有三种方法可以统计每个数出现的次数。
方法一是使用数组来记录每个数出现的次数。首先,定义一个数组s,长度为最大数加一。然后,遍历输入的数列num,对于每个数,将对应的s数组位置加一。最后,遍历s数组,输出每个数出现的次数。\[1\]
方法二是使用indexOf()方法。遍历输入的数列arr,对于每个数,使用indexOf()方法找到第一个出现的位置,然后再遍历数列arr,统计该数出现的次数。最后,输出每个数和它出现的次数。\[2\]
方法三是在原数组上进行记录。遍历输入的数列arr,对于每个数,将该数对应的位置加上数组的长度。然后,再次遍历数列arr,将每个数除以数组的长度,得到该数出现的次数。最后,输出每个数和它出现的次数。\[3\]
以上是三种不同的方法来统计每个数出现的次数。您可以根据具体的需求选择适合的方法。
#### 引用[.reference_title]
- *1* [【C语言】统计数字出现次数](https://blog.csdn.net/weixin_73464014/article/details/128877831)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [统计数组中每项出现的次数三种方法](https://blog.csdn.net/qq_44831135/article/details/116592097)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [统计每个数字出现的次数。](https://blog.csdn.net/kai8wei/article/details/45672355)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
并统计每个数出现的次数
好的,这是一个计数问题。您可以使用一个字典来记录每个数字出现的次数。具体的实现方法如下:
```python
# 定义一个列表
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 定义一个空字典
count_dict = {}
# 遍历列表,统计每个数字出现的次数
for num in nums:
if num in count_dict:
count_dict[num] += 1
else:
count_dict[num] = 1
# 打印每个数字出现的次数
for key, value in count_dict.items():
print(key, "出现了", value, "次")
```
输出结果为:
```
1 出现了 3 次
2 出现了 3 次
3 出现了 3 次
4 出现了 3 次
5 出现了 3 次
6 出现了 3 次
7 出现了 3 次
8 出现了 3 次
9 出现了 3 次
```