【问题标题】:How to search in a list across more elements unified in a single string and return the position?如何在单个字符串中统一的更多元素的列表中搜索并返回位置?
【发布时间】:2020-11-26 15:58:55
【问题描述】:

我有一个如下列表:

['56', '33 f6', '39 74 24 0c', '57', '74 07', '68 1c e0 40 00', 'eb 05', '68 18 e0 40 00', '68 10 e0 40 00', 'ff 15 18 81 40 00', '8b f8', '59', '3b fe', '59', '75 04', '33 c0']

假设我想搜索一个序列:

'33 f6 39 74 24 0c 57 74' 然后知道列表的哪些元素被覆盖。在这种情况下,它将是位置 2,3,4,5。

我想将列表统一在一个字符串中,然后通过find() 进行搜索。但我不知道如何前进。

有没有更好的方法在 Python 中做到这一点?

编辑:接受的解决方案效果很好!

【问题讨论】:

    标签: python python-3.x string list


    【解决方案1】:

    我能想到的最短版本:

    arr = ['56', '33 f6', '39 74 24 0c', '57', '74 07', '68 1c e0 40 00', 'eb 05', '68 18 e0 40 00', '68 10 e0 40 00', 'ff 15 18 81 40 00', '8b f8', '59', '3b fe', '59', '75 04', '33 c0']
    search_term = '33 f6 39 74 24 0c 57 74'
    joined = ' '.join(arr)
    search_index = joined.find(search_term)
    contained_indices = []
    counter = 0
    for i in range(len(arr)):
        if counter >= search_index and counter <= search_index + len(search_term):
            contained_indices.append(i)
        if counter >= search_index + len(search_term):
            break
        counter += len(arr[i])+1
    
    print(contained_indices)
    

    请注意,它使用从 0 开始的索引,如果您的当前数组中不再有整洁的结构,它可能会失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 2015-12-18
      • 2019-09-17
      • 1970-01-01
      相关资源
      最近更新 更多