检查清单中的特定序列 [英] Check for specific sequences in list

查看:99
本文介绍了检查清单中的特定序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我要检查,如果检查一个子列表是列表中present,并有出现的顺序列表中也是如此。如果子表为present在列表中的函数应返回true。如果不是它应该返回false。我创建试图做这样的功能,可有人告诉我,如果在正确的轨道或者我应该固定在IM,B / C,现在它不工作。

So, I have to check if to check if a sublist is present within the list and has to appear in the list in that order as well. If sublist is present in the list the function should return true. and if not it should return false. I created a function attempting to do this, can someone tell me if im on the right track or what I should fix, b/c right now it isn't working.

def subfunc(L,sublist):

  for i in range (len(L)):
        if L[i:i+len(sublist)] == sublist:
              print "true"
        else:
              print "false"

例如,如果子表是 [3,4] 键,列表是 [0,1,2,3,4,5] 它应该返回true。在该子表是事实 [5,1] 它应该返回false。

for example if the sublist was [3,4] and the list was [0,1,2,3,4,5] it should return true. In the case that the sublist was [5,1] it should have returned false.

推荐答案

这似乎工作并处理边缘情况:

This seems to work and handle the edge cases:

def subfunc(L,sublist):
    sublen = len(sublist)
    for i in xrange(len(L)-sublen+1):
        if L[i:i+sublen] == sublist:
            return True
    return False

L = [0,1,2,3,4,5]
print subfunc(L, [0,1])  # --> True
print subfunc(L, [5,1])  # --> False
print subfunc(L, [4,5])  # --> True

这篇关于检查清单中的特定序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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