2013-02-12 97 views
1

無法找到一個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

回答

0

不知道會是多少在性能方面改變,但你可以在第二種情況下寫一個過濾功能

例如(如果你正在尋找精確的匹配)

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

1

試圖回答這個問題,這部分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

相關問題