python统计列表中相同的数量代码
时间: 2024-04-29 14:22:30 浏览: 19
以下是Python统计一个列表中每个元素出现的次数的代码:
```python
from collections import Counter
lst = [1, 2, 3, 4, 1, 2, 3, 2, 2]
counts = Counter(lst)
for element, count in counts.items():
print(f"{element}: {count}")
```
输出结果:
```
1: 2
2: 4
3: 2
4: 1
```
以上代码用到了Python标准库`collections`中的`Counter`类。`Counter`是一个简单的计数器,用于统计可哈希对象(如整数、字符串等)的出现次数。在上面的代码中,我们先将列表转换为计数器对象,然后遍历计数器中的键值对,输出每个元素和它出现的次数。
相关问题
python统计列表中相同的数量并合并代码
可以使用Python内置的collections模块中的Counter类来完成该任务,代码如下:
```python
from collections import Counter
lst = [1, 2, 3, 2, 1, 1, 3, 4, 5, 4, 3]
count = Counter(lst)
merged = {key: value for key, value in count.items() if value > 1}
print(merged) # {1: 3, 2: 2, 3: 3, 4: 2}
```
以上代码中,首先我们定义了一个列表lst来存放需要统计的数据,然后用Counter(lst)来创建一个计数器对象count,用count.items()来获取每个元素以及它们的出现次数。接下来,我们使用一个字典推导式来筛选出出现次数大于1的元素,存放到一个名为merged的字典中。最后,我们通过print函数来打印合并后的结果。
python统计列表中相同字段的数量并按列表格式输出
可以使用Python的内置函数`collections`来统计列表中相同字段的数量。具体步骤如下:
1. 引入`collections`模块中的`Counter`类。
2. 创建一个空的`Counter`对象。
3. 遍历列表中的每个元素,使用`Counter`对象的`update`方法统计每个元素出现的次数。
4. 遍历`Counter`对象,按照出现次数从高到低排序,然后按照格式输出。
以下是一个示例代码:
```python
from collections import Counter
my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'pear', 'banana', 'banana']
counter = Counter()
for item in my_list:
counter.update({item: 1})
sorted_counter = sorted(counter.items(), key=lambda x: x[1], reverse=True)
for item, count in sorted_counter:
print(f"{item}: {count}")
```
输出结果为:
```
banana: 4
apple: 2
orange: 1
pear: 1
```
其中,`sorted_counter`是一个按照出现次数从高到低排序后的元素列表,每个元素是一个元组,第一个元素是元素值,第二个元素是出现次数。`print`语句使用了格式化字符串,输出了每个元素的值和出现次数。
相关推荐
![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)