如果一个人有一长串数字:
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但那不管用吗?
发布于 2011-12-12 15:13:15
这应该可以处理几乎所有的情况,包括一个子列表出现多次:
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]发布于 2011-12-12 15:00:26
这是可行的,但这只是因为我依赖于子列表存在于其内部的事实。
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]]https://stackoverflow.com/questions/8470852
复制相似问题