list-comprehension - python - 有什么更好的方法来写列表推导?

我正在尝试从artist姓名中删除空格和"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]



作者:

如果你认为列表推导中的表达式太大,最好直接使用for循环。


 [artist.lower().replace('the , '').replace(' ','') for artist in artist_list]



或者,使用正则表达式,整个过程可能更简单,更灵活:


>>> re.sub(r'($the)|[ ]', '', 'The Artist Formerly Known As Prince')


'TheArtistFormerlyKnownAsPrince'



作者:


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]



作者:
...