python - 查找(开始:end) positions that sublists occur within a list . Python

标签 python list find position sublist

如果有一长串数字:

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/

相关文章:

python - 如何避免 youtube-dl 中的 No-SSL-CERTIFICATE 错误?

python - Django、Turbo Gears、Web2Py,哪个更好?

python - 我怎样才能将这些数字放入列表中?

linux - 列出包含已编辑文件的目录

jquery - 在 HTML 字符串中查找元素

linux - 打印 Cscope 符号链接(symbolic link)的绝对路径

python - 如何使用python检测复选框

python - 将 matplotlib 条形图添加到 PDF

Android 传感器 ListView

java - 如何使用 java8 通过谓词对列表进行分区?