如果有一长串数字:
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
但这行不通?
最佳答案
这应该可以处理几乎任何情况,包括出现不止一次的子列表:
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]
关于python - 查找(开始:end) positions that sublists occur within a list . Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8470852/