每个嵌套列表中的元素数

时间:2015-09-07 01:19:25

标签: python python-2.7 python-3.x

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

我需要在每个嵌套列表中打印A,B,C和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中编写代码吗?

3 个答案:

答案 0 :(得分: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})
---

答案 1 :(得分:0)

一种简单易懂的方法是检查A,B和C并将1加到计数器上。

nested_list = [['A','B','A','A'],['C','C','B','B'],['A','C','B','B']]

number_of_a = 0
number_of_b = 0
number_of_c = 0


for lists in nested_list:
    for item in lists:
        if item == 'A':
             number_of_a += 1
        elif item == 'B':
             number_of_b += 1
        elif item == 'C':
             number_of_c += 1

print number_of_a, number_of_b, number_of_c

快乐的编码,祝你好运!

答案 2 :(得分:0)

使用collections.Counter似乎是最干净的方式。 但是,你可以尝试这个,想法是使用字典来跟踪每个元素出现的次数。 (虽然未经测试的代码)。

for list in nested_list:
    dict = {}
    for element in list:
        if not dict[element]:
            dict[element] = 1
        else:
            dict[element] += 1
    print(dict)
    print(count(dict))