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.
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.
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 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] 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