如何将Python的clean_strigs函数改写为单列表推导式?
Hey there! I see you're trying to convert that nested-loop string cleaner into a concise list comprehension—let's get this sorted out.
First, let's recap what your original code does: for each string in the input list, it runs through all the cleaning functions in sequence (title casing, removing punctuation, trimming whitespace) and collects the final cleaned results. To replicate this logic in a single list comprehension, we can use functools.reduce to chain all the cleaning functions into one operation for each string.
Step-by-Step Solution
- First, import
reducefromfunctools(it’s a standard library tool built for applying a sequence of operations to a value). - Use
reduceinside the list comprehension to apply every cleaning function to each string in order—this replaces the nested loops entirely.
Here's the corrected, refactored code that produces your expected output:
import re from functools import reduce states = { 1:['Alabama@ ', 'Georgia!', 'Geor%gia%%', 'georgia', 'FlOrIda', 'southcarolina##', 'West virginia?']} def remove_punctuations(value): return re.sub('[#!?@%]','',value) cleaning_steps = [str.title, remove_punctuations, str.strip] # The single list comprehension you're looking for cleaned_strings = [ reduce(lambda val, func: func(val), cleaning_steps, s) for s in states[1] ] print(cleaned_strings) # Output: ['Alabama', 'Georgia', 'GeorGia', 'Georgia', 'Florida', 'Southcarolina', 'West Virginia']
How It Works
reduce(lambda val, func: func(val), cleaning_steps, s)takes the initial strings, then applies each function incleaning_stepsone after another. This behaves exactly like your original nested loops: firststr.title()formats the string, thenremove_punctuations()strips special characters, thenstr.strip()trims leftover whitespace—matching your desired output perfectly.
Quick Notes on Your Original Code
Just a tiny heads-up: your original function had a typo (clean_strigs instead of clean_strings) and the return statement was incorrectly indented (it should sit inside the function). The list comprehension approach avoids these small pitfalls entirely!
内容的提问来源于stack exchange,提问作者Shaelander Chauhan

