In daily development, we may encounter the need to modify list elements in bulk. You can use list derivatives to quickly achieve this, here are some technical summaries for reference.
One, modify individual words (not recommended):
aaa=['Black','Red','White','Black'] aaa=str(aaa) bbb=("Black.","Yellow.") bbb in the end: "['yellow', 'red', 'white', 'yellow']"
II. Modifying individual words
lists = ['Magical', 'CIC', 'Securities', 'Limited', 'Today', 'Investment', 'up', 'One', 'Paragraph',"Fantastic.",'The Game'] new_lists =['Miracle' if i =='Magical' else i for i in lists] #-----output---------- ['Miracle', 'CIC', 'Securities', 'Limited', 'Today', 'Investment', 'up', 'One', 'Paragraph', 'Miracle', 'The Game']
Third, use the list to modify multiple words
lists = ['Magical', 'CIC', 'Securities', 'Limited', 'Today', 'Investment', 'up', 'One', 'Paragraph',"Miracles.",'The Game'] replace_list = ['Magical',"Miracles."] new_lists =['Miracle' if i in replace_list else i for i in lists] #-----output---------- ['Miracle', 'CIC', 'Securities', 'Limited', 'Today', 'Investment', 'up', 'One', 'Paragraph', 'Miracle', 'The Game']
Fourth, use a dictionary to modify multiple words
lists = ['Magical', 'CIC', 'Securities', 'Limited', 'Today', 'Investment', 'up', 'One', 'Paragraph',"Miracles.",'The Game'] replace_dict = {'Magical':"Fantasy.","Miracles.":"Miracle."} new_lists =[replace_dict[i] if i in replace_dict else i for i in lists] #-----output---------- ['Fantasy', 'CIC', 'Securities', 'Limited', 'Today', 'Investment', 'up', 'One', 'Paragraph', 'Miracle', 'The Game']
Here it is most convenient and powerful to use a dictionary to modify to generate a new list. So it is recommended to use this last method.
More aboutpython batch modify replace elements in listPlease check out the related links below for articles on