python 列表和子列表

发布于 2024-10-19 09:33:49 字数 450 浏览 7 评论 0原文

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

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 循环感到困惑,而且我不知道从这里到哪里去修复我的代码。请指点?

它应该做什么的示例:

  check([4,0],[9,1,4,6,8,9])
  True
  check([1,2],[2,3,1])
  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

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?

example of what it should do:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

殊姿 2024-10-26 09:33:49

我认为问题需要递归地解决,所以我这样做了:

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,这会导致调用堆栈冒泡并返回。

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

Edit:

Brief explanation:

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.

桃气十足 2024-10-26 09:33:49

您可以从以下内容开始:

set(lst1).issubset(lst2)

查看 lst1 是否包含在 lst2 中,忽略顺序。如果它通过了一个列表包含在另一个列表中的测试,那么您可以执行以下操作:

ii = lst2.index(lst1[0])
if lst2[ii:ii+len(lst1)] == lst1:
   return True
else:
   return False

最初我声明第一个检查与第二个检查无关,尽管您必须正确处理 ValueError 如果 lst1 的第一个元素不在 lst2 中。

编辑:
顺便说一句,我将我的代码版本与 yan 的代码版本进行了比较,我的代码版本在几乎所有用例下都明显更快,特别是如果 len(lst1) 更大(与 yan 的实现相比,加速高达 200 倍)。使用 timeit 模块尝试一下。

def check(lst1,lst2):
    try:
        ii = lst2.index(lst1[0])
    except ValueError:
        return False

    if lst2[ii:ii+len(lst1)] == lst1:
        return True
    else:
        return False 

作为其工作原理的解释 ii = lst2.index(lst1[0])lst2 中查找与 lst1 的第一个元素匹配的索引>。如果 lst2 中缺少该项目,它会捕获 ValueError 并返回 False。如果该元素确实存在,则 lst2[ii:ii+len(lst1)] == lst1 会将所有 lst1lst2 的子列表进行比较从匹配的元素开始并获取下一个 len(lst) 元素。

You could start with something like:

set(lst1).issubset(lst2)

to see if lst1 is contained within lst2 ignoring order. If it passes the test that one list is contained within the other, then you could do something like:

ii = lst2.index(lst1[0])
if lst2[ii:ii+len(lst1)] == lst1:
   return True
else:
   return False

Originally I stated that the first check was irrelevant given the second, although you'd have to properly handle the ValueError if the first element of lst1 is not in lst2.

Edit:
Just as a side note, I compared a version of my code vs yan's and mine is significantly faster under almost all use cases, especially if len(lst1) is larger (up to 200x speedup vs yan's implementation). Give it a try with the timeit module.

def check(lst1,lst2):
    try:
        ii = lst2.index(lst1[0])
    except ValueError:
        return False

    if lst2[ii:ii+len(lst1)] == lst1:
        return True
    else:
        return False 

As an explanation of how it works ii = lst2.index(lst1[0]) finds the index in lst2 that matches the first element of lst1. If that item is missing from lst2 it catches the ValueError and returns False. If that element does exist, lst2[ii:ii+len(lst1)] == lst1 compares all of lst1 vs the sublist of lst2 starting from the matched element and taking the next len(lst) elements.

七度光 2024-10-26 09:33:49
>>> a=[9,1,4,6,8,9]
>>> by_twos=zip(a, a[1:])
>>> by_twos
[(9, 1), (1, 4), (4, 6), (6, 8), (8, 9)]
>>> (4,6) in by_twos
True
>>> a=[9,1,4,6,8,9]
>>> by_twos=zip(a, a[1:])
>>> by_twos
[(9, 1), (1, 4), (4, 6), (6, 8), (8, 9)]
>>> (4,6) in by_twos
True
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文