Filter list of strings using list comprehension

后端 未结 1 1679
终归单人心
终归单人心 2021-01-18 07:55
>>> li = [\"a b self\", \"mpilgrim\", \"foo c\", \"b\", \"c\", \"b\", \"d\", \"d\"]
>>> condition = [\"b\", \"c\", \"d\"]
>>> [elem for el         


        
相关标签:
1条回答
  • 2021-01-18 08:18

    Assuming the code needs to retrieve all the strings that contain any of the conditions strings:

    [elem for elem in li if any(c in elem for c in condition)]
    

    In case a full match of a condition is required:

    [elem for elem in li if
     any(re.search('(^|\s){}(\s|$)'.format(c), elem) for c in condition)]
    

    Edit: This can be simplified to a single pre-defined regex:

    predicate = re.compile('(^|\s)({})(\s|$)'.format('|'.join(condition)))
    
    [elem for elem in li if predicate.search(elem)]
    
    0 讨论(0)
提交回复
热议问题