python统计出现次数_Python统计列表中的重复项出现的次数的方法
时间: 2023-11-17 10:07:11 浏览: 40
可以使用 Python 的 Counter 模块来统计列表中元素出现的次数。具体做法如下:
```python
from collections import Counter
lst = [1, 2, 3, 4, 1, 2, 3, 1, 2, 1]
cnt = Counter(lst)
for k, v in cnt.items():
print(f"{k}出现了{v}次")
```
输出结果为:
```
1出现了4次
2出现了3次
3出现了2次
4出现了1次
```
其中,Counter(lst) 可以返回一个字典,记录 lst 中每个元素出现的次数。然后使用 items() 方法遍历字典,输出每个元素和它出现的次数即可。
相关问题
python 计算一个数在列表中出现次数_Python统计列表(List)中的重复项出现的次数并进行排序...
可以使用Python内置的`collections`模块中的`Counter`类来统计列表中元素出现的次数,然后再进行排序。下面是一个示例代码:
```python
from collections import Counter
# 定义一个列表
my_list = [1, 2, 3, 4, 2, 3, 1, 2, 1, 3]
# 使用Counter统计元素出现次数
count = Counter(my_list)
# 对出现次数进行排序,并返回一个列表
result = sorted(count.items(), key=lambda x: x[1], reverse=True)
print(result)
```
输出结果如下:
```
[(2, 3), (1, 3), (3, 3), (4, 1)]
```
其中,元素2、1、3都出现了3次,元素4只出现了1次。列表`result`中的元素是一个元组,第一个元素是元素的值,第二个元素是该元素在列表中出现的次数。通过`sorted`函数对元组进行排序,可以得到一个按照出现次数从大到小排列的列表。
用python编写一个统计列表中每个字母出现的次数
可以用 Python 中的字典(dict)来实现这个功能,具体代码如下:
```python
lst = ['a', 'b', 'c', 'a', 'b', 'd'] # 统计的列表
# 初始化一个空字典
count_dict = {}
# 遍历列表中的每个元素,统计每个字母出现的次数
for ele in lst:
if ele in count_dict:
count_dict[ele] += 1
else:
count_dict[ele] = 1
# 输出每个字母出现的次数
for k, v in count_dict.items():
print("{}: {}".format(k, v))
```
输出结果为:
```
a: 2
b: 2
c: 1
d: 1
```
在这个例子中,我们首先定义了一个包含重复元素的列表 `lst`。然后,我们初始化了一个空字典 `count_dict`,用于统计每个字母出现的次数。接下来,我们遍历列表中的每个元素,如果该元素已经在字典中出现过,则将该元素对应的值加 1;否则,将该元素添加到字典中,并将其对应的值设置为 1。最后,我们遍历字典中的每个键值对,并输出每个字母出现的次数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)