python中查看每列重复元素的个数
时间: 2024-05-04 19:18:11 浏览: 19
可以使用Python中的collections模块中的Counter类来实现这个功能。假设有一个列表`lst`,可以按照如下方式查看每列重复元素的个数:
```python
from collections import Counter
# 假设有一个列表lst
lst = [
[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[7, 8, 9],
[4, 5, 6]
]
# 使用zip函数将列表转化为元组的列表,然后对每一列应用Counter类
for col, count in zip(range(len(lst[0])), map(Counter, zip(*lst))):
print(f"第{col + 1}列有如下元素出现次数:{count}")
```
输出:
```
第1列有如下元素出现次数:Counter({1: 2, 4: 2, 7: 1})
第2列有如下元素出现次数:Counter({2: 2, 5: 2, 8: 1})
第3列有如下元素出现次数:Counter({3: 2, 6: 2, 9: 1})
```
这里使用了zip函数将列表转化为元组的列表,然后对每一列应用Counter类,最后输出每列中每个元素出现的次数。
相关问题
python中计算每列重复元素的个数
可以使用Python中的collections模块中的Counter类来实现。
假设你有一个二维列表,每列包含一些元素,你想要计算每列中重复元素的个数,可以按照以下步骤进行操作:
1. 首先导入collections模块中的Counter类:
```python
from collections import Counter
```
2. 假设你的二维列表为data,可以使用zip函数将其转置成元素为列的列表:
```python
transposed_data = zip(*data)
```
3. 然后使用列表推导式计算每列中重复元素的个数,将其存储在一个列表中:
```python
counts = [Counter(col) for col in transposed_data]
```
完整代码示例:
```python
from collections import Counter
data = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
transposed_data = zip(*data)
counts = [Counter(col) for col in transposed_data]
print(counts)
```
输出结果为:
```
[Counter({1: 1, 2: 1, 3: 1, 4: 1}),
Counter({2: 1, 3: 1, 4: 1, 5: 1}),
Counter({3: 1, 4: 1, 5: 1, 6: 1})]
```
其中每个Counter对象包含每列中元素出现的次数。
python计数列表中重复元素的个数
你可以使用Python标准库collections中的Counter函数来计算列表中各元素出现的次数。具体可以参考如下代码:
```
from collections import Counter
my_list = [1, 2, 3, 1, 2, 3, 4, 5]
counted = Counter(my_list)
for element, count in counted.items():
print(f"{element}: {count}")
```
输出结果为:
```
1: 2
2: 2
3: 2
4: 1
5: 1
```
其中元素1,2,3出现了2次,元素4,5各出现了1次。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)