python列表和子列表 [英] python list and sublist

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

问题描述

我必须检查list2中是否包含list1.它还应该检查它是否也以该顺序出现在列表中.如果为true,则返回true,否则返回false.

I have to check if list1 is contained in list2. It also should check if it appears in that order in the list as well. If it's true, it should return true and false if it doesn't.

def check(lst1, lst2):
for x in lst1:
    for y in lst2:
        xx = lst1.sort()
        yy = lst2
        if xx != yy:
            return False
        else:
            return True

我让自己陷入for循环的困惑,而且,我也不知道该从哪里修复我的代码.请问指针?

I'm confusing myself with the for loops and also, I don't know where to go from here to fix my code. Pointers please?

应做的事示例:

  check([4,0],[9,1,4,6,8,9])
  True
  check([1,2],[2,3,1])
  False

推荐答案

我认为问题是希望以递归的方式解决,所以我做到了:

I thought the problem was begging to be solved recursively, so I did:

def check(needle, haystack):
  if not needle:
      return True
  try:
    offset = haystack.index(needle[0])
    return check(needle[1:], haystack[offset+1:])
  except:
    return False

简要说明:

首先,我们检查要查找的列表是否为空(一旦开始调用自己,这一点就很重要),因为所有列表中都有空列表,因此我们返回True.然后,我们尝试在要查找的列表中查找要查找的列表的第一项.如果找到它,我们将再次调用该函数,但是要稍微改变一下参数:我们已经查看了"needle"的第一项,并在"haystack"中看到了它.因此,现在我们需要检查"needle"的其余部分是否在"haystack"的其余部分中.因此,我们仅使用两个列表的其余部分再次调用该函数.剩下的所有东西都是除第一个元素以外的所有东西,而大海捞针的其余部分则是我们发现的所有东西之后的所有东西.如果我们到达第一个列表为空的位置,则意味着我们在大海捞针中找到了它.如果发生异常,则找不到所需的内容,因此我们返回False,这会使调用堆栈冒泡并得到返回.

First we check if the list we're looking for is empty (this is important once we start calling ourselves), since all lists have the empty list inside it, we return True. Then we try finding the first item of the list we're looking for in the list we're looking at. If we find it, we then call the function again, but change the arguments a bit: we already looked at the first item of the 'needle' and saw it in the 'haystack'. So now we need to check if the remainder of 'needle' is in the remainder of 'haystack'. So we call the function again only with the remainder of both lists. The remainder of needle is everything but the first element, and the remainder of haystack is all items after the one we found. If we get to a point where the first list is empty, it means we found it in the haystack. If we get an exception, what we were looking for wasn't found, so we return False, which bubbles up the call stack and gets returned.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆