Finding whether a string starts with one of a list's variable-length prefixes

后端 未结 11 2162
傲寒
傲寒 2021-01-01 12:16

I need to find out whether a name starts with any of a list\'s prefixes and then remove it, like:

if name[:2] in [\"i_\", \"c_\", \"m_\", \"l_\", \"d_\", \"t         


        
11条回答
  •  情深已故
    2021-01-01 13:08

    When it comes to search and efficiency always thinks of indexing techniques to improve your algorithms. If you have a long list of prefixes you can use an in-memory index by simple indexing the prefixes by the first character into a dict.

    This solution is only worth if you had a long list of prefixes and performance becomes an issue.

    pref = ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"]
    
    #indexing prefixes in a dict. Do this only once.
    d = dict()
    for x in pref:
            if not x[0] in d:
                    d[x[0]] = list()
            d[x[0]].append(x)
    
    
    name = "c_abcdf"
    
    #lookup in d to only check elements with the same first character.
    result = filter(lambda x: name.startswith(x),\
                            [] if name[0] not in d else d[name[0]])
    print result
    

提交回复
热议问题