2015-10-30 66 views
1

如何檢查列表中的某個元素是否存在於另一個列表中?是否將它追加到另一個列表中。如何獲取所有值在列表中?如何檢查列表中的某個元素是否存在於另一個列表

common=[] 

def findCommon(interActor,interActor1): 
    for a in interActor: 
     if a in interActor1: 
      common.append(a) 
    return common 
interActor=['Rishi Kapoor','kalkidan','Aishwarya'] 
interActor1=['Aishwarya','Suman Ranganathan','Rishi Kapoor'] 
+0

什麼不起作用? – ppperry

+1

你需要在函數內部放置'common'初始化。然後在調用它時將函數結果分配給一個變量。 – Barmar

回答

9

你可以通過遍歷的做到這一點:

common = [x for x in iter_actor1 if x in iter_actor2] 

或使用集:

common = set(iter_actor1).intersection(iter_actor2) 
1
interActor=['Rishi Kapoor','kalkidan','Aishwarya'] 
interActor1=['Aishwarya','Suman Ranganathan','Rishi Kapoor'] 
anotherlist = [] 

for x in interActor: 
    if x in interActor1: 
     anotherlist.append(x) 
+0

它應該在一個函數中,以便它可以被使用多次。 – Barmar

相關問題