Find and replace multiple values in python

前端 未结 6 1200
攒了一身酷
攒了一身酷 2021-02-15 03:59

I want to find and replace multiple values in an 1D array / list with new ones.

In example for a list

a=[2, 3, 2, 5, 4, 4, 1, 2]

I woul

6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-15 04:43

    To replace values in a list using two other lists as key:value pairs there are several approaches. All of them use "list compression".

    Using list.index():

    a=[2, 3, 2, 5, 4, 4, 1, 2]
    val_old=[1, 2, 3, 4, 5] 
    val_new=[2, 3, 4, 5, 1]
    a_new=[val_new[val_old.index(x)] for x in a]
    

    Using your special case:

    a=[2, 3, 2, 5, 4, 4, 1, 2]
    a_new=[x % 5 + 1 for x in a]
    

提交回复
热议问题