Python-行数/列数的计数出现在

时间:2019-02-27 16:09:53

标签: python

说我有一个二维的字符串数组,如下所示:

A = [['a', 'b', 'b'],
     ['c', 'c', 'a'],
     ['d', 'c', 'a']]

,我想找出给定元素出现在多少行中,以便获得输出:

In [1]: get_number_rows('a')
Out[1]: 3

In [2]: get_number_rows('b')
Out[2]: 1

In [1]: get_number_rows('c')
Out[1]: 2

In [2]: get_number_rows('d')
Out[2]: 1

请注意,我不希望出现'a'的总数,而是希望它出现的行数。

我试图遍历行并简单地计数,但是我正在处理非常大的数据集(1000s x 1000s),所以它非常慢。任何更快的解决方案将不胜感激。

3 个答案:

答案 0 :(得分:1)

如果包含字符的数组数量,可以使用以下get_number_rows()方法求和:

A = [['a', 'b', 'b'],
     ['c', 'c', 'a'],
     ['d', 'c', 'a']]

def get_number_rows(char):
    return len([x for x in A if char in x])

get_number_rows('a')
>> 3

get_number_rows('b')
>> 1

get_number_rows('c')
>> 2

get_number_rows('d')
>> 1

答案 1 :(得分:1)

对于行,请尝试类似

len([x for x in A if 'a' in x])

此列表理解使x中满足A的所有列表'a' in x的列表。然后,您可以使用该列表的长度来获取总数。

答案 2 :(得分:0)

if __name__ == "__main__":
    A = [['a', 'b', 'b'],
         ['c', 'c', 'a'],
         ['d', 'c', 'a']]

    def get_number_rows(A, desired_element):
        """
        Pass in two dimensional array, A as first parameter
        Pass in desired char element, desired_element as 2nd parameter.
        Function will return number of occurrences of desired_element in A.
        """

        element_count = 0  # Int to keep track of occurrences
        for group in A:  # For nested array in A
            if desired_element in group:  # If our desired element is in the sub array
                element_count += 1  # Increment our counter
        return element_count  # After completion, return the counter

    print(get_number_rows(A, 'a'))

    print(get_number_rows(A, 'b'))

    print(get_number_rows(A, 'c'))

    print(get_number_rows(A, 'd'))