[英]How do I check if a list (list_1) contains the same elements located in same order of another list (list_2)?
我有 2 个列表:list_1 和 list_2。
list_1: ['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now']
我有
list_2: ['yeah', 'i', 'watched', 'the', 'world']
和
list_3: ['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched']
我想检查list_2
中的元素是否以相同的顺序出现在list_1
中,在这种情况下
['yeah', 'i', 'watched', 'the', 'world']
无论 list_1 中的起始位置和结束位置如何。
但是,当我比较 list_3 和 list_2 时,虽然 list_2 中的所有元素都出现在 list_3 中,但它们的排序不同。
在第一种情况下(list_1 vs list_2),答案为真。 在第二种情况下(list_3 vs list_2),答案为 False。
这是代码。 如果您在函数中输入 2 列表,该函数将检查第二个列表中的所有元素是否都在第一个列表中,并且两个列表中的顺序相同。
list_1= ['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now']
list_2= ['yeah', 'i', 'watched', 'the', 'world']
list_3= ['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched']
def check(ref_list, check_list):
matching=0
for i in range(len(ref_list)):
if check_list[0]==ref_list[i] and check_list[1]==ref_list[i+1]:
for j in range(len(check_list)):
if check_list[j]==ref_list[i+j]:
matching=1
else:
matching=0
if j==len(check_list)-1:
if matching==1:
print("checking list Matched with reference")
return 0
else:
print("Didn't match")
return 0
if matching==0:
print("Didn't match")
return 0
check(list_1,list_2)
方法:
从 list1 的开头开始
环形:
在 list1 的剩余部分中找到 list2 的单词的位置。
如果不在 list1 中,则返回 False。
def match( list2, list1):
i0 = 0 # start point in list1
for i2 in range( len( list2)):
for i1 in range( i0, len( list1)):
if list1[i1]==list2[i2]:
i0 = i1 # next search will start here
break
else:
return False # not found
return True # match
list1= ['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now']
list2= ['yeah', 'i', 'watched', 'the', 'world']
list3= ['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched']
match( list2, list1) # return True
match( list2, list3) # return False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.