Closed. This question needs to be more focused。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
                        
                        4年前关闭。
                                                                                            
                
        
我有一个嵌套列表:
[[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


谁能告诉我如何用python编写代码?

最佳答案

您可以使用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})
---

关于python - 每个嵌套列表中的元素数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32429932/

10-12 23:03