在Python中查找子列表在列表中出现的位置(起始:end)。

3
如果有一份很长的数字列表:
example=['130','90','150','123','133','120','160','45','67','55','34']

在列表中还有子列表,如下:

sub_lists=[['130','90','150'],['90','150'],['120','160','45','67']]

如何生成一个函数,输入这些子列表,然后输出它们在原始字符串中出现的位置? 获取结果的方法:
results=[[0-2],[1-2],[5-8]]

我在尝试类似于以下的东西

example=['130','90','150','123','133','120','160','45','67','55','34']

sub_lists=[['130','90','150'],['90','150'],['120','160','45','67']]

for p in range(len(example)):
    for lists in sub_lists:
        if lists in example:
            print p

但是那个方法不起作用了吗?


我理解results=[[0-2],[1-2],[5-8]]只是您自己的表示法,以说明您想要返回的数字,如果您真的想将其作为字符串获取,您应该使用字符串替换。类似于return "result=[[%d-%d], [%d-%d..." % (<sequence of values here>) - mac
可能是重复的问题:Python:在列表中查找子列表的起始和结束索引 - Nikana Reklawyks
2个回答

3

这应该可以处理几乎所有情况,包括子列表出现多次的情况:

example=['130','90','150','123','133','120','160','45','67','55','34']
sub_lists=[['130','90','150'],['90','150'],['120','160','45','67']]

for i in range(len(example)):
    for li in sub_lists:
        length = len(li)
        if example[i:i+length] == li:
            print 'List %s has been matched at index [%d, %d]' % (li, i, i+length-1)

输出:

List ['130', '90', '150'] has been matched at index [0, 2]
List ['90', '150'] has been matched at index [1, 2]
List ['120', '160', '45', '67'] has been matched at index [5, 8]

2
这个方法可以奏效,但前提是子列表完整存在。
example=['130','90','150','123','133','120','160','45','67','55','34']

sub_lists=[['130','90','150'],['90','150'],['120','160','45','67']]

def f(example, sub_lists) :
    for l in sub_lists:
        yield [example.index(l[0]),example.index(l[-1])]

print [x for x in f(example,sub_lists)]

>>> [[0, 2], [1, 2], [5, 8]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接