Python 每个嵌套列表中的元素数

Python 每个嵌套列表中的元素数,python,python-2.7,python-3.x,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 有谁能告

我有一个嵌套列表,如下所示: [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编写此代码吗?

您可以使用:

您可以使用:


一种简单易懂的方法是只检查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

祝您编码愉快,祝您好运

一种简单易懂的方法是检查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

祝您编码愉快,祝您好运

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


使用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))