我有两个列表:
list1=['lo0','lo1','te123','te234']
list2=['lo0','first','lo1','second','lo2','third','te123','fourth']我想要写一段python代码来打印list2的下一个元素,其中list1的项出现在list2中,否则写成"no-match",即,我希望输出为:
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中不存在元素的情况下导致“不匹配”。请指点一下!提前谢谢。
发布于 2016-09-25 03:25:06
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")发布于 2016-09-25 03:46:46
您可以使用带有集合的enumerate来测试成员资格,如果找到集合中的元素,则使用当前元素索引+1打印list2中的下一个元素:
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")发布于 2016-09-25 18:31:44
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 matchhttps://stackoverflow.com/questions/39679940
复制相似问题