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]



...