简体   繁体   中英

Search replace patterns in a Python list

I have a list of Rubik's Cube movements and a dictionary of shortcuts like this :

mvts = ['U', 'U', 'R', 'Ri', 'L2', ...]
shortcuts = {'UU' : 'U2', 'RRi' : '', ...}

What I'm trying to do is applying a "search and replace" on the mvts list based on the contents of shortcuts .

Here is what the result would be in the example :

mvts = ['U2', 'L2', ...]

I'm using Python3 and I can't use a library that doesn't come with Python from scratch.

I'm stuck. I can do this with some regex on a String but I don't see how to make this search quick on my list.

Try this :

for i in range(len(mvts)):
      if(mvts[i] in shortcuts):
           mvts[i] = shortcuts[mvts[i]]

Notice

If you are Already sure that list elements exist in dictionary you can delete if line

and if you want delete duplications in list:

mvts = list(set(mvts))

You could use re.sub

import re

mvts = ['UUU', 'U', 'R', 'Ri', 'L2']
shortcuts = {'UU' : 'U2', 'RRi' : ''}

def do_sub(m):
    for k, v in shortcuts.items():
        m = re.sub(k, v, m)
    return m

[do_sub(m) for m in mvts]

Output:

['U2U', 'U', 'R', 'Ri', 'L2']

I've found a solution by googling with the good terms : "Search/replace sublist in list Python".

So I've used @latty's solution explained here https://stackoverflow.com/a/12898180/2058840 .

I had to change my dictionary structure to :

shortcuts = {'U U' : ['U2'], 'R Ri' : '', ...}

And then :

for (sublist, shortcut) in shortcuts:
    replace_list(mvts, sublist.split(), shortcut) #@latty's function

Thanks @martin-konecny and @arman for your help !

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