简体   繁体   中英

Using a dictionary to replace characters in a list of strings

I have the following dictionary:

clues = {'A': '#', 'N': '%', 'M': '*'}

I also have the following list:

puzzle = ['#+/084&"', '#3w#%#+', '8%203*','']

How can I replace the items from the list (ie by referencing the values from 'clues') with the keys in 'clues' so it would now appear the following way:

puzzle = ['A+/084&"', 'A3wANA+', '8N203M','']

Create a translation map from your dictionary, then use str.translate() :

try:
    # Python 3
    maketrans = str.maketrans
except AttributeError:
    # Python 2
    from string import maketrans

m = maketrans(''.join(clues.values()), ''.join(clues))
result = [s.translate(m) for s in puzzle]

This does assume the values in clues are unique. str.translate() is by far the fastest method to map single characters to other single characters.

Demo (using Python 2.7):

>>> from string import maketrans
>>> clues = {'A': '#', 'N': '%', 'M': '*'}
>>> puzzle = ['#+/084&"', '#3w#%#+', '8%203*', '']
>>> m = maketrans(''.join(clues.values()), ''.join(clues))
>>> [s.translate(m) for s in puzzle]
['A+/084&"', 'A3wANA+', '8N203M', '']
puzzle = ['#+/084&"', '#3w#%#+', '8%203*','']
clues = {'A': '#', 'N': '%', 'M': '*'}
answer = []
for p in puzzle:
    for dest,src in clues.items():
        p = p.replace(src,dest)
    answer.append(d)

You could do:

for key, value in clues.iteritems():
    puzzle = [ a.replace(value,key) for a in puzzle]

To test it:

>>> clues = {'A': '#', 'N': '%', 'M': '*'}
>>> puzzle = ['#+/084&"', '#3w#%#+', '8%203*','']
>>> for key, value in clues.iteritems():
...     puzzle = [ a.replace(value,key) for a in puzzle]
...
>>> puzzle
['A+/084&"', 'A3wANA+', '8N203M', '']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM