每个嵌套列表中的元素数

Exp*_*SDN 1 python python-2.7 python-3.x

我有一个嵌套列表:[[A,B,A,A],[C,C,B,B],[A,C,B,B]] .....等等

我需要在每个嵌套列表中打印A,B和C的数量.并且还打印每个嵌套列表中的元素总数:

For first nested list:
A = 3
B = 1
#Should not print C!
total = 4

For second nested list:
C = 2
B = 2
#Should not print A!
total = 4

...
...
...
so on
Run Code Online (Sandbox Code Playgroud)

谁能告诉我如何在python中编码?

Sai*_*ait 5

你可以使用collections.Counter:

>>> from collections import Counter
>>> bigList = [['A','B','A','A'],['C','C','B','B'],['A','C','B','B']]
>>> for index,subList in enumerate(bigList):
...    print(index)
...    print(Counter(subList))
...    print('---')
...
0
Counter({'A': 3, 'B': 1})
---
1
Counter({'C': 2, 'B': 2})
---
2
Counter({'B': 2, 'A': 1, 'C': 1})
---
Run Code Online (Sandbox Code Playgroud)