+ 2

How to return the number of elements that satisfy a specific condition within a list in Python?

CONSIDER THE FOLLOWING LIST - TO FIND THE NUMBER OF ELEMENTS THAT CONTAIN CHARACTER "n" list1 = ["Chennai","Bangalore","Delhi","25","67",100,25.2,"University"] strlist = [str(list1) for list1 in list1] #casting the values of the list as string for i in range(0,len(strlist)): n=strlist[i].find("n") if (n!= -1): print(strlist[i]) THIS COULD PRINT THE ELEMENTS CONTAINING THE CHARACTER "n" IN THE LIST BUT HOW DO I PRINT THE NUMBER OF ELEMENTS(THE COUNT) THAT CONTAIN CHARACTER "n" ??? [i.e. the no. of elements that contain "n" within the list = 3] any ideas peeps!?!?!?

2nd Sep 2020, 8:34 PM
Lakshmi Aravindarajan
Lakshmi Aravindarajan - avatar
8 Réponses
+ 3
Incrementing a variable say count whenever n is found in a list item list1 = ["Chennai","Bangalore","Delhi","25","67",100,25.2,"University"] strlist = [str(list1) for list1 in list1] #casting the values of the list as string count=0; for i in range(0,len(strlist)): n=strlist[i].find("n") if (n!= -1): count+=1 print(count) Edit: another Alternative to do this as a one-liner is using list comprehension and through functional programming print(len(list(filter(lambda x:"n" in x,list(str(i) for i in list1)))))
2nd Sep 2020, 8:39 PM
Abhay
Abhay - avatar
+ 5
A possible solution: list1 = ["Chennai","Bangalore","Delhi","25","67",100,25.2,"University"] print(len([i for i in list1 if 'n' in str(i)]))
3rd Sep 2020, 6:05 PM
Lothar
Lothar - avatar
+ 3
You can use this for element in list1: if n in element : nb_element+=1 nb_n += element.count('n')
2nd Sep 2020, 8:41 PM
Nathan Sikati
Nathan Sikati - avatar
+ 3
3rd Sep 2020, 4:41 AM
Lakshmi Aravindarajan
Lakshmi Aravindarajan - avatar
+ 3
Mirielle thks for letting me know
3rd Sep 2020, 3:21 PM
Abhay
Abhay - avatar
+ 2
list1 = [ "Chennai","Bangalore","Delhi","25","67",100,25.2, "University"] strlist = list( filter( lambda x : 'n' in str(x), list1 ) ) # 👆 Only if true, added to list print(strlist) print(len(strlist))
2nd Sep 2020, 9:03 PM
Jayakrishna 🇮🇳