本文介绍了检查列表是否是子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查 list1 是否是 list2 的子列表(真;如果 list2 中与 list1 相同的每个整数都与 list1 中的索引顺序相同)

I need to check if list1 is a sublist of list2 (True; if every integer in list2 that is common with list1 is in the same order of indexes as in 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

谁能帮帮我...为什么这不起作用?

Can anybody help me... why isn't this working?

推荐答案

您的代码不起作用,因为只要 ls1 中的列表元素没有出现在 ls2 中,它就会立即返回 False.

Your code isn't working because as soon as a list element in ls1 doesn't occur in ls2 it will return False immediately.

这将创建两个仅包含公共元素(但按其原始顺序)的列表,然后在它们相同时返回 True:

This creates two lists that contain only the common elements (but in their original order) and then returns True when they are the same:

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

这篇关于检查列表是否是子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 11:45
查看更多