python - Finding how many of a certain character in each element in a list -


i want find how many ' '(whitespaces) there in each of these sentences happen elements in list. so, for: ['this sentence', 'this 1 more sentence'] calling element 0 return value of 3, , calling element 1 return value of 4. having trouble doing both of finding whitespaces looping through every element find 1 highest number of whitespaces.

have simple list-coprehension using count

>>> lst = ['this sentence', 'this 1 more sentence'] >>> [i.count(' ') in lst] [3, 4] 

other ways include using map

>>> map(lambda x:x.count(' '),lst) [3, 4] 

if want callable (which function iterates through list have mentioned) can implemented

>>> def countspace(x): ...     return x.count(' ') ...  

and executed as

>>> in lst: ...     print countspace(i) ...  3 4 

this can solved using regexes using re module mentioned below grijesh

>>> import re >>> [len(re.findall(r"\s", i)) in lst] [3, 4] 

post edit

as need find max element also, can do

>>> vals = [i.count(' ') in lst]  >>> lst[vals.index(max(vals))] 'this 1 more sentence' 

this can implemented callable using

>>> def getmax(lst): ...     vals = [i.count(' ') in lst] ...     maxel = lst[vals.index(max(vals))] ...     return (vals,maxel) 

and use

>>> getmax(lst) ([3, 4], 'this 1 more sentence') 

post comment edit

>>> s = 'this sentence. 1 more sentence' >>> lst = s.split('. ') >>> [i.count(' ') in lst] [3, 4] 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -