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

后端 未结 11 2136
傲寒
傲寒 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 12:50

    What about using filter?

    prefs = ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"]
    name = list(filter(lambda item: not any(item.startswith(prefix) for prefix in prefs), name))
    

    Note that the comparison of each list item against the prefixes efficiently halts on the first match. This behaviour is guaranteed by the any function that returns as soon as it finds a True value, eg:

    def gen():
        print("yielding False")
        yield False
        print("yielding True")
        yield True
        print("yielding False again")
        yield False
    
    >>> any(gen()) # last two lines of gen() are not performed
    yielding False
    yielding True
    True
    

    Or, using re.match instead of startswith:

    import re
    patt = '|'.join(["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"])
    name = list(filter(lambda item: not re.match(patt, item), name))
    

提交回复
热议问题