2017-07-26 68 views
0

我有3個數組l1,l2 & l3並且列表中的每個元素在整個列表中都是唯一的。我有另一個數組q,它需要檢查數組l1,l2,& l3,如果它存在,則它應該輸出數組名稱查找類似的值存在於多個列表中

注意:q的值可能介於l1, L1或L3

示例列表:

q= ['abc','def','ghi',' gggg','cc '] 
l1 = ['aa abc','bb bb','cc cc'] 
l2 = ['ddd ddd','eee def eee','fff fff'] 
l3 = ['gggg gggg','hhhh hhhh','ghi iiii'] 

代碼應該是這樣的

for value in q 
    if value in l1: 
    do something 
    elif value in l2: 
    do something 
    elif value in l2: 
    do something 
    else: 
    "nil" 

的輸出中應該是:

l1 
l2 
l3 
l3 
l1 

在此先感謝..

回答

1

既然你正在處理,你需要檢查各個元素在每個列表子:

q = ['abc','def','ghi',' gggg','cc '] 
l1 = ['aa abc','bb bb','cc cc'] 
l2 = ['ddd ddd','eee def eee','fff fff'] 
l3 = ['gggg gggg','hhhh hhhh','ghi iiii'] 
all_lists = [l1, l2, l3] 

for val in q: 
    for i, li in enumerate(all_lists): 
     for li_val in li: 
      if val in li_val: 
       print('{} is in l{}'.format(val, i + 1)) 

輸出:

abc is in l1 
def is in l2 
ghi is in l3 
gggg is in l3 
cc is in l1 

注意您不能直接訪問列表的名稱,因爲對象不會跟蹤引用它們的名稱。你可以使用字典,但名字仍然需要硬編碼。

0

試試這個

q= ['abc','def','ghi',' gggg','cc '] 
l1 = ['abc','bb bb','cc cc'] 
l2 = ['ddd ddd','eee def eee','fff fff'] 
l3 = ['gggg gggg','hhhh hhhh','ghi iiii'] 

for stri in (q): 
    for i,l in enumerate([l1,l2,l3]): 
     if(filter(lambda x:stri in x, l)): 
      print stri +" found in l"+str(i+1) 
相關問題