how to count() within list index

Viewed 167

I have a two dimensional list.

[[3, 3, 5],
[3, 2, 8],
[2, 1, 3]]

I want to count how many times 3 appears as the first value of each list within this list, preferably without iterating through.

6 Answers

One way without using for loop:

len(list(filter(lambda x: x[0] == 3, arr)))

Output:

2

Try this sum with a list comprehension:

print(sum([i[0] == 3 for i in lst]))

Output:

2
from collections import Counter


lst = [[3, 3, 5],
[3, 2, 8],
[2, 1, 3]]


print (Counter(sublist[0] for sublist in lst)[3])

You can use the Counter function. Mention which position you want to look at in sublist, and which key (i.e. integer 3) you want to print the result for.

Output:

2

Using numpy only:

import numpy as np

a = [[3, 3, 5],
[3, 2, 8],
[2, 1, 3]]
b = a[:, 0]
c = np.where(b == 3)
print(c[0].shape[0])

Using pandas only:

import pandas as pd

a = [[3, 3, 5],
[3, 2, 8],
[2, 1, 3]]
df = pd.DataFrame(a)
print(df[df[0] == 3].shape[0])

Output:

2

I think chain from itertools might be the solution if you don't want to use loops

from itertools import chain
t=[[1, 2, 3], [3, 5, 6], [7], [8, 9]]
new_list = list(chain(*t))
print(new_list)

Output [1, 2, 3, 3, 5, 6, 7, 8, 9]

After this you can just use count function this 'new_list' to check the count of any elements

All what you need is to check the order of the entered number in terms of slicing and comparison.

According to python 3.8

Code Syntax

lists = [[3, 3, 5], [3, 2, 8], [2, 1, 3]]
num = int(input("check our number: "))
counter = 0
for each in lists:
    if num == each[0]:
        counter +=1
    
print (f" your {num} occur found: {counter} times ")

Output

check our number: 3
 your 3 occur found: 2 times

[Program finished]
Related