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.

BOBTHEBUILDER
  • 345
  • 1
  • 4
  • 20
  • 4
    What do you mean "without iterating the list"? Do you want to avoid for loops and list comprehensions for some reason? – Bill Lynch Jan 04 '21 at 04:34
  • Does this answer your question? [How do I flatten a list of lists/nested lists?](https://stackoverflow.com/questions/20112776/how-do-i-flatten-a-list-of-lists-nested-lists) – Sachin Rajput Jan 04 '21 at 05:21

6 Answers6

7

One way without using for loop:

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

Output:

2
Chris
  • 29,127
  • 3
  • 28
  • 51
1

Try this sum with a list comprehension:

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

Output:

2
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
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
Synthase
  • 5,849
  • 2
  • 12
  • 34
  • Isn't this expensive since we are only interested in a fixed position in each of the elements in the list of lists? – codeforester Jan 04 '21 at 04:37
  • 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. – Synthase Jan 04 '21 at 04:39
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
Memphis Meng
  • 1,267
  • 2
  • 13
  • 34
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

Sachin Rajput
  • 238
  • 7
  • 26
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]
Ahmed
  • 796
  • 1
  • 5
  • 16