我需要检查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



