2

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.

2
  • 4
    What do you mean "without iterating the list"? Do you want to avoid for loops and list comprehensions for some reason? Commented Jan 4, 2021 at 4:34
  • Does this answer your question? How do I flatten a list of lists/nested lists? Commented Jan 4, 2021 at 5:21

6 Answers 6

7

One way without using for loop:

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

Output:

2 
Sign up to request clarification or add additional context in comments.

Comments

1

Try this sum with a list comprehension:

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

Output:

2 

1 Comment

that counts every value but I'm only looking for specific indexes. in this example the correct output would be 2.
0
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 

2 Comments

Isn't this expensive since we are only interested in a fixed position in each of the elements in the list of lists?
Certainly, but who knows what the OP wants to make with it after. And if limited to the question, being expansive is not a problem considering the length of the data.
0

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 

Comments

0

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] 

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.