比较两个列表并使用循环打印下一个元素

时间:2016-09-24 19:03:19

标签: python-2.7

我有两个清单:

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

我想编写一个python代码来打印list2的下一个元素,其中list1的项目存在于list2中,否则写入“不匹配”,即我希望输出为:

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

我无法想象如何引发list2中不存在元素的“不匹配”。请指导!提前谢谢。

3 个答案:

答案 0 :(得分: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])

或者你可以包括一个try,除非要包含一个例程,如果该项是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")

答案 1 :(得分:0)

您可以使用枚举来测试成员身份,如果您找到该集合中的元素然后打印下一个list2中的元素使用当前元素index + 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',你也不能使用索引,好像你有重复的单词一样,你总会得到第一个匹配。

将您自己的逻辑与double for循环匹配并进行O(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")

答案 2 :(得分: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'

Out put:

first
second
fourth
No match