You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python的clean_strigs函数改写为单列表推导式?

How to Rewrite the String Cleaning Function as a Single List Comprehension

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

  1. First, import reduce from functools (it’s a standard library tool built for applying a sequence of operations to a value).
  2. Use reduce inside 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 string s, then applies each function in cleaning_steps one after another. This behaves exactly like your original nested loops: first str.title() formats the string, then remove_punctuations() strips special characters, then str.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 15:57:43