【问题标题】:Find (start:end) positions that sublists occur within a list . Python查找子列表出现在列表中的(开始:结束)位置。 Python
【发布时间】:2012-01-18 05:49:13
【问题描述】:

如果一个人有一长串数字:

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

但这不起作用?

【问题讨论】:

  • 我认为results=[[0-2],[1-2],[5-8]] 只是您自己的符号来说明您想要返回的数字,如果您真的想将其作为字符串获取,您应该使用字符串替换。类似return "result=[[%d-%d], [%d-%d..." % (<sequence of values here>)

标签: python list find position sublist


【解决方案1】:

这应该可以处理几乎所有情况,包括出现不止一次的子列表:

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]

【讨论】:

    【解决方案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]]
    

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 1970-01-01
      • 2019-12-08
      • 2018-10-22
      • 2020-04-26
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多