在列表中查找子列表出现的(start:end)位置。Python
如果你有一长串数字:
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 个回答
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]]
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]