检查列表是否为子列表
问题内容:
我需要检查list1是否为list2的子列表(正确;如果list2中与list1相同的每个整数的索引顺序与list1相同)
def sublist(lst1,lst2):
for i in range(len(lst1)):
if lst1[i] not in lst2:
return False
for j in range(len(lst2)):
if (lst1[j] in lst2) and (lst2.index(lst1[i+1]) > lst2.index(lst1[i])):
return True
谁能帮我…为什么这样不起作用?
问题答案:
我需要检查list1是否是list2的子列表(是正确的;如果list2中与list1相同的每个整数的索引顺序与list1相同)
您的代码无法正常工作,因为ls2中没有出现ls1中的列表元素,它将立即返回False。
这将创建两个仅包含公共元素(但按其原始顺序)的列表,然后在它们相同时返回True:
def sublist(lst1, lst2):
ls1 = [element for element in lst1 if element in lst2]
ls2 = [element for element in lst2 if element in lst1]
return ls1 == ls2
编辑: 一种内存有效的变体:
def sublist(ls1, ls2):
'''
>>> sublist([], [1,2,3])
True
>>> sublist([1,2,3,4], [2,5,3])
True
>>> sublist([1,2,3,4], [0,3,2])
False
>>> sublist([1,2,3,4], [1,2,5,6,7,8,5,76,4,3])
False
'''
def get_all_in(one, another):
for element in one:
if element in another:
yield element
for x1, x2 in zip(get_all_in(ls1, ls2), get_all_in(ls2, ls1)):
if x1 != x2:
return False
return True