查找子列表在列表中出现的(开始:结束)位置。蟒蛇

时间:2011-12-12 06:53:09

标签: python list find position sublist

如果有一长串的数字:

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

但那不起作用?

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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]]