3

If one had a long list of numbers:

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

and sub lists within the list like

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

how would you generate a function that takes these sublists and gives you the positions that they occurred in the original string? to get the results:

results=[[0-2],[1-2],[5-8]]

I was trying something along the lines of

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

but that was not working?

O.rka
  • 29,847
  • 68
  • 194
  • 309
  • I take that `results=[[0-2],[1-2],[5-8]]` was just your own notation to illustrate what numbers you wanted to be returned, if you really wanted to obtain that as a string, you should use string substitution. Something like `return "result=[[%d-%d], [%d-%d..." % ()`. – mac Dec 12 '11 at 07:20
  • Possible duplicate of [Python: Find starting and ending indices of sublist in list](http://stackoverflow.com/questions/17870544/python-find-starting-and-ending-indices-of-sublist-in-list) – Nikana Reklawyks Feb 02 '16 at 19:46

2 Answers2

3

This should handle almost any case, including a sublist being present more than once:

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)

Outputs:

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]
mac
  • 42,153
  • 26
  • 121
  • 131
2

This works, but only because I depend on the facts that the sublists exists in their interity

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]]
Pengman
  • 708
  • 6
  • 12