如何在Python中匹配两个列表中的项目

2 投票
2 回答
9082 浏览
提问于 2025-04-17 15:40

我在找一种用Python来匹配两个列表中元素的方法,但不想用很多“for”循环和“if”判断。我希望能找到更简单的办法。我现在有一些很大的循环,要遍历多个列表来进行匹配。如果匹配成功,我想把这些元素从列表中删除。这里有两个例子:

def score_and_retweet(auth):
    api = tweepy.API(auth)
    for tweet in api.home_timeline(count=100, include_rts=0):
        for goodword in tweet_whitelist:
            if goodword in tweet.text and tweet.retweet_count >= 2:
                try:
                    api.retweet(tweet.id_str)
                except tweepy.error.TweepError:
                    error_id = tweet.id_str

还有

t = time.localtime()
    if t.tm_hour is 14 and (t.tm_wday is 1 or t.tm_wday is 4):
        htmlfiles = glob.glob(html_file_dir+'/*.html')
        for file in htmlfiles:
            for badword in filename_badwords:
                if badword in file:
                    try:
                        htmlfiles.remove(file)
                    except ValueError:
                        error = "already removed"

2 个回答

6

在回答这个问题的某一部分时,matching elements of one list against elements in another list,可以使用 set() 这个方法,比如:

a = ['a','b','c','d','g']
b = ['a','c','g','f','z']

list(set(a).intersection(b)) # returns common elements in the two lists
2

不太确定这样做在性能上会有多大变化,但你可以写一个过滤函数。

比如在第二种情况下(如果你想找完全匹配的结果)

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

然后使用:

goodFiles = filter(fileFilter, htmlfiles)

这个方法相比于集合交集的好处是,你可以让过滤函数变得非常复杂(在你第一个例子中有多个条件)。

撰写回答