+ 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!?!?!?
8 Respuestas
+ 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)))))
+ 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)]))
+ 3
You can use this
for element in list1:
if n in element :
nb_element+=1
nb_n += element.count('n')
+ 3
+ 3
Mirielle thks for letting me know
+ 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))