如何将一个列表中的项目与Python中另一个列表中的项目进行匹配

问题描述:

无法找到一个python解决方案来匹配另一个列表中的元素而没有整个“for”和“if”循环。我希望找到一个更好的方式来做到这一点。我有一些大的迭代循环通过多个列表来执行匹配。在比赛中,我希望删除列表中的元素。这里有两个例子:如何将一个列表中的项目与Python中另一个列表中的项目进行匹配

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" 
+0

你可以对列表进行排序吗?如果是这样,你可以在1次扫描中完成。 – smk 2013-02-12 22:08:35

+0

对于你的问题不是一个真正的答案,但是在你的第一个例子中,你可以将'tweet.retweet_count> = 2'条件移到'tweet_whitelist'循环中for forword的外部 - 如果条件已经存在,则不需要执行循环假。 (如果'if'有'else'则忽略这个。) – andersschuller 2013-02-12 22:11:50

+1

如果维护顺序没有关系,那就是'set',并且还有一个有序的配方。然后你会得到设定的操作,为你做所有这些事情。 – 2013-02-12 22:13:20

不知道会是多少在性能方面改变,但你可以在第二种情况下写一个过滤功能

例如(如果你正在寻找精确的匹配)

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

然后使用:

goodFiles = filter(fileFilter, htmlfiles) 

优势这个拥有交集是可以使过滤功能复杂,只要你想(你有你的第一个例子多个条件)

+0

好主意。我会试试这个。 – 2013-02-13 00:30:12

+0

刚刚使用它,它效果很好!非常感谢你! – 2013-02-13 02:03:42

试图回答这个问题,这部分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 
+0

感谢您的回复!我怎么能在“如果X在Y:”这种情况下做到这一点。我想查看列表A中的某个项是否包含在B中的某个字符串中? – 2013-02-13 00:31:18