Python.replace()中的双For循环问题
这感觉是一个非常简单的解决方案,但我无法实现:Python.replace()中的双For循环问题,python,for-loop,Python,For Loop,这感觉是一个非常简单的解决方案,但我无法实现: def cleaning(recipe): #make every element lowercase recipe = [str.lower(i) for i in recipe] #remove punctuations chars = "\\`\'\"*_{}[]%&()>#+-.!$" for c in chars: for item in recipe:
def cleaning(recipe):
#make every element lowercase
recipe = [str.lower(i) for i in recipe]
#remove punctuations
chars = "\\`\'\"*_{}[]%&()>#+-.!$"
for c in chars:
for item in recipe:
if c in item:
item = item.replace(c,'')
return recipe
如果我使用此函数并运行此函数
blah = ['Salt', 'Hot&Sour Sauce']
blah = cleaning(blah)
我得到:
['salt', 'hot&sour sauce']
字符替换未生效。
感觉这是一个非常基本的问题,有人能指出快速解决方法吗
谢谢 您正在更新项,但不更新包含项的列表
chars = "\\`\'\"*_{}[]%&()>#+-.!$"
recipe = ['Salt', 'Hot&Sour Sauce']
print(recipe)
for c in chars:
for i, item in enumerate(recipe):
if c in item:
item = item.replace(c,'')
recipe[i] = item # here the list is updated.
print(recipe)
['Salt', 'Hot&Sour Sauce']
['Salt', 'HotSour Sauce']
问题在于:
for c in chars:
for item in recipe:
if c in item:
item = item.replace(c,'')
您正在为项
引用分配一个新字符串,但这不会更改列表中的值。迭代索引(例如,范围内i的(len(recipe))…recipe[i]=new_string
)或使用不同的策略,可能不涉及嵌套循环
>>> r = ['Salt', 'Hot&Sour Sauce']
您可以使用正则表达式:
>>> import re
>>> def cleaning(recipe):
... return list(map(lambda item: re.sub(r'''[\\`'"*_{}\[\]%&()>#+-.!$]*''', '', item.lower()), recipe))
...
>>> cleaning(r)
['salt', 'hotsour sauce']
或过滤器:
>>> def cleaning(recipe):
... return [''.join(filter(lambda i: i not in "\\`\'\"*_{}[]%&()>#+-.!$", item.lower())) for item in recipe]
...
>>> cleaning(r)
['salt', 'hotsour sauce']
如果不显式地将out赋值给列表中的条目,则无法实际修改列表。换句话说,执行item=item.replace(c),
对recipe
没有任何作用
< >您可以通过枚举来修改列表以工作,但您可能需要考虑映射或列表理解,就像您将<代码>配方>代码>转换为小写一样。在这种情况下,您可以使用特殊情况下的str.translate
,其中表
参数为None
,而deletechars
参数为标点符号
现在可以根据映射或列表理解重写函数。例如:
def cleaning(recipe):
punc = "\\`\'\"*_{}[]%&()>#+-.!$"
rm_punc = lambda s: str.translate(s.lower(), None, punc) #Special case of str.translate.
return map(rm_punc, recipe) #Remove the punctuation.
blah = ['Salt', 'Hot&Sour Sauce']
blah = cleaning(blah)
print blah
印刷品:
['salt', 'hotsour sauce']
您正在使用项创建副本。replace()
调用…然后不会用副本覆盖列表元素的当前值。您是否希望结果是['salt','hotsour sause']
?顺便说一句,这是完成这项工作的正确工具。您可以通过直接在s.lower()上执行translate
来摆脱第二个map
。lower()
@TigerhawkT3:Updated。谢谢你接电话。