jane
jane

Reputation: 63

Finding the number of occurrences of an element in every list inside a list

Here I have a nested list:

[['a,b,c,d,e’], [‘d,e,c,b,a’], [‘e,b,a,e,c’], ['a,c,b,e,d'], [‘e,d,c,b,a’], [‘a,c,b,d,e']]

I want to count the number of occurrences of "a" in the beginning of each list, so that will be 3. I also want to be able to do the same for each letter in the lists, so I know that the number of "b" in the second position of each list is 2. This is perhaps easier to imagine if you put each list on top of each other and look down the column.

I want to be able to give the letter and position to scan through and receive the number of occurrences of that letter in that position. I hope I'm clear.

Here is what I have tried so far:

number=sum(x.count("a") for x in data[0][0])

Upvotes: 0

Views: 71

Answers (2)

Aaditya Ura
Aaditya Ura

Reputation: 12669

You should use a function instead of just loops. Because it's easier to give a parameter as index no and letter:

Here is solution with a function:

list_1= [['a,b,c,d,e'], ['d,e,c,b,a'], ['e,b,a,e,c'], ['a,c,b,e,d'], ['e,d,c,b,a'], ['a,c,b,d,e']]

    def find(index,letter,list_1):
        count=0
        for item in list_1:
            for subitem in item:
                if subitem[index]==letter:
                    count+=1
        return count

Test with 'a' with index 0:

print(find(0, 'a', list_1))

Output:

3

Test with 'b' with index 2:

print(find(2, 'b', list_1))

Output:

2

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

In most simple case you may use the following:

data = [['a,b,c,d,e'], ['d,e,c,b,a'], ['e,b,a,e,c'], ['a,c,b,e,d'], ['e,d,c,b,a'], ['a,c,b,d,e']]
letter = 'b'
pos = 1
result = sum(1 for i in data if letter in i[0] and i[0].split(',')[pos] == letter)

print(result)

The output:

2

To get a more accurate and robust solution:

data = [['a,b,c,d,e'], ['d,e,c,b,a'], ['e,b,a,e,c'], ['a,c,b,e,d'], ['e,d,c,b,a'], ['a,c,b,d,e']]
letter = 'b'
pos = 1
result = 0

for i in data:
    if letter in i[0]:
        items = i[0].split(',')
        if pos < len(items) and items[pos] == letter:
            result += 1

print(result)

Upvotes: 1

Related Questions