Issue
states = { 1:['Alabama@ ', 'Georgia!', 'Geor%gia%%', 'georgia', 'FlOrIda', 'southcarolina##', 'West virginia?']}
def remove_punctuations(value):
return re.sub('[#!?@%]','',value) # remove these punctuations
for_strings = [str.title, remove_punctuations, str.strip] # perform these actions on strings
def clean_strigs(strings,options):
result = []
for val in strings:
#print(val)
for function in options:
val = function(val)
result.append(val)
return result
filter_dictonary(states[1],for_strings)
output = ['Alabama',
'Georgia',
'GeorGia',
'Georgia',
'Florida',
'Southcarolina',
'West Virginia']
I am trying to write the clean_string function in a with comprehension and also trying to call for_list inside it but I am unable to do so I tried the below code
def filter_column(strings,for_strings):
result = [val for value in strings for function in for_strings for val in function(val) ]
return result
Can some help me with writing this?
summary: Just write the above clean_strigs in a single list comprehension
Solution
You can use the below solution. It should work.
result = [reduce(lambda a, func: func(a), [value] + for_strings) for value in states[1] ]
The problem with nested for loop in list comprehension is that result of the previous function will not propagate to the next function. That is where reduce comes to help.
Hope this helps.
Answered By - Durai
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.