Python batch replace elements in a list

In daily development, we may encounter the need to modify list elements in batches. You can use the list comprehension to quickly implement it. Here are some technical summaries for reference.

One, modify a single word

lists = ['神奇', '建投', '证券', '有限公司', '今天', '投资', '了', '一', '款',"神奇",'游戏']

new_lists =['奇迹' if i =='神奇' else i for i in lists]

#-----output----------
['奇迹', '建投', '证券', '有限公司', '今天', '投资', '了', '一', '款', '奇迹', '游戏']

Second, use the list to modify multiple words

lists = ['神奇', '建投', '证券', '有限公司', '今天', '投资', '了', '一', '款',"神迹",'游戏']
replace_list = ['神奇',"神迹"]

new_lists =['奇迹' if i in replace_list else i for i in lists]

#-----output----------
['奇迹', '建投', '证券', '有限公司', '今天', '投资', '了', '一', '款', '奇迹', '游戏']

Three, use the dictionary to modify multiple words

lists = ['神奇', '建投', '证券', '有限公司', '今天', '投资', '了', '一', '款',"神迹",'游戏']
replace_dict = {
    
    '神奇':"奇幻","神迹":"奇迹"}

new_lists =[replace_dict[i] if i in replace_dict else i for i in lists]

#-----output----------
['奇幻', '建投', '证券', '有限公司', '今天', '投资', '了', '一', '款', '奇迹', '游戏']

It is the most convenient and powerful to use the dictionary to modify and generate a new list here. Therefore, the last method is recommended.

Guess you like

Origin blog.csdn.net/TFATS/article/details/108625708