2016-09-24 43 views
0

我有兩個列表打印下一個元素:比較兩個列表,並使用循環

list1=['lo0','lo1','te123','te234'] 
list2=['lo0','first','lo1','second','lo2','third','te123','fourth'] 

我想寫一個Python代碼打印列表2的下一個元素,其中列表1的產品出現在列表2,其他的寫「不匹配」,即我想要的輸出:

first 
second 
no-match 
fourth 

我想出了下面的代碼:

for i1 in range(len(list2)): 
     for i2 in range(len(list1)): 
      if list1[i2]==rlist2[i1]: 
       desc.write(list2[i1+1]) 
       desc.write('\n') 

但給出的輸出爲:

first 
second 
fourth 

我不知道如何誘導「不匹配」,其中的元素不在列表2中。請指導!提前致謝。

回答

0
list1=['lo0','lo1','te123','te234'] 
list2=['lo0','first','l01','second','lo2','third','te123','fourth'] 

for i in list1: 
    if i not in list2: 
     print('no-match') 
    else: 
     print(list2[list2.index(i)+1]) 

或者你可能包括一試,除了包括常規,如果該項目是在list2中的最後一個值。

list1=['lo0','lo1','te123','te234','fourth'] 
list2=['lo0','first','l01','second','lo2','third','te123','fourth'] 

for i in list1: 
    if i not in list2: 
     print('no-match') 
    else: 
     try:    
      print(list2[list2.index(i)+1]) 
     except IndexError: 
      print(str(i)+" is last item in the list2") 
+0

不,它的作用是它將list1的每個元素與list2的每個元素進行比較,併爲每個不相等的元素打印不匹配的結果,即輸出很多不匹配和一些匹配的字符串,這些不是我在這裏要求的。 – Anjali

0

您可以使用枚舉設置來測試會員,如果發現是集合的元素,然後從列表2使用當前的元素索引+ 1打印下一個元素:

list1=['lo0','lo1','te123','te234',"tel23"] 
list2=['lo0','first','l01','second','lo2','third','te123','fourth'] 
st = set(list1) 

# set start to one to always be one index ahead 
for ind, ele in enumerate(list2, start=1): 
    # if we get a match and it is not the last element from list2 
    # print the following element. 
    if ele in st and ind < len(list2): 
     print(list2[ind]) 
    else: 
     print("No match") 

正確的答案也是:

first 
No match 
second 
No match 
No match 
No match 
fourth 
No match 

'l01'不等於'lo1',你也不能像使用重複單詞那樣使用索引,你總是會得到第一個匹配。

要與雙for循環和做Ø符合自己的邏輯(N^* 2)比較:

for ind, ele in enumerate(list2, start=1): 
    for ele2 in list1: 
     if ele == ele2 and ind < len(list2): 
      print(list2[ind]) 
     else: 
      print("No match") 
+0

它將list1的每個元素與list2的每個元素進行比較,併爲每個不相等的元素打印不匹配,即輸出很多不匹配和一些匹配的字符串。它不會根據我的要求提供輸出。 – Anjali

+0

@Anjali,你需要的輸出是錯誤的'第一,第二,第四'在列表1'中'l01''? –

+0

我已將我的問題編輯爲lo1! – Anjali

0
list1=['lo0','lo1','te123','te234'] 
list2=['lo0','first','lo1','second','lo2','third','te123','fourth'] 
res=[] 
for elm in list1: 
    if elm in list2: 
     print list2[list2.index(elm)+1] 
    else : 
     print 'No match' 

輸出地說:

first 
second 
fourth 
No match