Find and replace multiple values in python

前端 未结 6 1331
攒了一身酷
攒了一身酷 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
    2021-02-15 04:52

    In vanilla Python, without the speed of numpy or pandas, this is one way:

    a = [2, 3, 2, 5, 4, 4, 1, 2]
    val_old = [1, 2, 3, 4, 5]
    val_new = [2, 3, 4, 5, 1]
    expected_a_new = [3, 4, 3, 1, 5, 5, 2, 3]
    d = dict(zip(val_old, val_new))
    a_new = [d.get(e, e) for e in a]
    print a_new # [3, 4, 3, 1, 5, 5, 2, 3]
    print a_new == expected_a_new # True
    

    The average time complexity for this algorithm is O(M + N) where M is the length of your "translation list" and N is the length of list a.

提交回复
热议问题