1
A = ['d','a','c','a','a','d','a','d','c','e']
B = ['a','d','c','e']
C = ['z','x', 'y','k']

As you can see from above, I have three lists. List A is a random mix of characters, and B is a reordering of elements in the A list by frequency without duplicating them. The list C is the values I want to replace. I would like to check if the values in list B are in A and change the values in list A to those in list C. If there is a value 'B[0]' in list A, I would like to change all 'B[0]' values in list A change to C[0]. The rest of the elements also want to do so.

What I want:

A=['x','z','y','z','z','x','z','x','y','k']

3 Answers3

2

You could make a translation dict out of B and C and use a list comprehension.

>>> d = dict(zip(B, C))
>>> [d[x] for x in A]
['x', 'z', 'y', 'z', 'z', 'x', 'z', 'x', 'y', 'k']

If some values in A may not be in B, you could replace d[x] with something like d.get(x, x).

And if you need to overwrite the values of A, use slice assignment:

A[:] = [d[x] for x in A]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
2

Create a dictionary that maps characters to be replaced with their replacement and substitute the characters in a list comprehension:

A = ['d','a','c','a','a','d','a','d','c','e']
B = ['a','d','c','e']
C = ['z','x', 'y','k']

subs = dict(zip(B, C))
A = [subs[c] for c in A]

>>> A
['x', 'z', 'y', 'z', 'z', 'x', 'z', 'x', 'y', 'k']

We can assume that subs[c] will always succeed because B is derived from A and therefore all items in B must also be present in A.

If that were not the case then you could use dict.get() instead:

A = [subs.get(c, c) for c in A]
mhawke
  • 84,695
  • 9
  • 117
  • 138
1

I think the easiest way would be to create a dictionary with keys B to values C and use that dictionary to replace the values in A.

A = ['d','a','c','a','a','d','a','d','c','e']
B = ['a','d','c','e']
C = ['z','x', 'y','k']

char_dict = dict(zip(B, C))
for i, char in enumerate(A):
    A[i] = char_dict[char]

This can also be done using list comprehension

char_dict = dict(zip(B, C))
A = [char_dict[char] for char in A]
Jacob Lee
  • 4,405
  • 2
  • 16
  • 37