2011-12-12 123 views
2

如果一个有编号的一个长长的清单:像查找(开始:结束)列表中的子列表。 Python的

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

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

和子列表列表中你会如何生成一个函数,这些子列表,让您的位置,他们发生在原始字符串中? 得到的结果:

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 

线的东西,但是,这不是工作?

+0

我采取'结果= [0-2],[1-2],[5-8]'只是你自己的符号来说明什么ñ如果你真的想把它作为一个字符串来获取,你应该使用字符串替换。像'return'result = [[%d-%d],[%d-%d ...“%(<数值序列>))。 – mac

+0

[Python:查找列表中子列表的起始和结束索引]的可能重复(http://stackoverflow.com/questions/17870544/python-find-starting-and-ending-indices-of-sublist-in-list) –

回答

2

这应该处理几乎任何情况下,包括一个子表存在不止一次:

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

这工作,但只是因为我依赖于子列表存在于他们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]]