Sort a list of strings based on regular expression match

后端 未结 4 499
别跟我提以往
别跟我提以往 2021-01-14 02:33

I have a text file that looks a bit like:

random text random text, can be anything blabla %A blabla
random text random text, can be anything blabla %D blabla         


        
4条回答
  •  余生分开走
    2021-01-14 03:35

    In [1]: def grp(pat, txt): 
       ...:     r = re.search(pat, txt)
       ...:     return r.group(0) if r else '&'
    
    In [2]: y
    Out[2]: 
    ['random text random text, can be anything blabla %A blabla',
     'random text random text, can be anything blabla %D blabla',
     'random text random text, can be anything blabla blabla %F',
     'random text random text, can be anything blabla blabla',
     'random text random text, %C can be anything blabla blabla']
    
    In [3]: y.sort(key=lambda l: grp("%\w", l))
    
    In [4]: y
    Out[4]: 
    ['random text random text, can be anything blabla %A blabla',
     'random text random text, %C can be anything blabla blabla',
     'random text random text, can be anything blabla %D blabla',
     'random text random text, can be anything blabla blabla %F',
     'random text random text, can be anything blabla blabla']
    

提交回复
热议问题