我正在尝试从歌手姓名中删除空格和'the'。但是我的列表理解似乎不可读。
有没有更好的方法来编写此列表理解,或者我只使用经典的for循环?
new_list= [artist.lower().replace(' ','') if artist[0:3] != 'the' else artist.lower().replace(' ','')[3:] for artist in artist_list]
您可以将理解与正则表达式结合起来:
import re
new_list = [re.sub("^the ", "", artist.lower()).replace(" ", "") for artist in artist_list]
将棘手的位提取到函数中仍然不违法:
def cleanup(artist):
artist = artist.lower().replace(' ', '')
if artist.startswith('the'):
artist = artist[3:]
return artist
new_list = [cleanup(artist) for artist in artist_list]
这具有很大的优势(在我看来,您可以分别测试和调试部件,并且很清楚每个步骤在做什么。]
顺便说一句,您将要立即测试和调试清理部分,因为这种方法会对他们可能成为巨人产生奇怪的影响。
您以为正确,如果列表理解中的表达式太大,最好使用直接的for循环。
也就是说,可以通过应用str.replace()删除'the'而无需测试来简化表达式(replace在没有替换的情况下是静默的:]
>>> s = 'The Artist Formerly Known as Prince'
>>> s.lower().replace('the ', '').replace(' ', '')
'artistformerlyknownasprince'
或者,使用正则表达式,整个过程可能更简单,更灵活:
>>> re.sub(r'(^the)|\s', '', s.lower())
'artistformerlyknownasprince'