How do I match items in one list against items in another list in Python

前端 未结 2 449
故里飘歌
故里飘歌 2020-12-11 10:34

Having trouble finding a python solution to matching elements of one list against elements in another list without a whole pile of \"for\" and \"if\" loops. I\'m hoping to f

相关标签:
2条回答
  • 2020-12-11 11:20

    Not sure how much it would change in terms of performance, but you could write a filter function

    For example in the second case (if you're looking for exact matches)

    def fileFilter(f):
        if f in filename_badwords:
            return False
        else:
            return True
    

    Then use:

    goodFiles = filter(fileFilter, htmlfiles)
    

    The advantage this has over set intersection is you can make the filter function as complex as you want (you have multiple conditions in your first example)

    0 讨论(0)
  • 2020-12-11 11:22

    Trying to answer this part of the question matching elements of one list against elements in another list could use set(), for example:

    a = ['a','b','c','d','g']
    b = ['a','c','g','f','z']
    
    list(set(a).intersection(b)) # returns common elements in the two lists
    
    0 讨论(0)
提交回复
热议问题