如何在字符串中找到字符串的多个出现并在空格分隔的列表中返回其位置的索引?

时间:2018-05-17 23:54:41

标签: python

我在这里有一个功能:

def get_books(msg):
    results = []

    for key, value in books.items():
        for item in value:
            if item in msg:
                last_item = item.split(" ")[-1]
                msg_split = msg.split(" ")

                if last_item in msg_split:
                    index = msg_split.index(last_item)
                    results.append((key, index))

    return results

我需要找到一种能够让这个功能检测到多个同名书籍的方法。

例如,Exodus 1:1 blah blah blah John 1:2会返回[("exod", 0), ("john", 5)],但Exodus 1:1 blah blah blah Exodus 1:2只会返回[("exod", 0)]

我如何能够修改我的函数,以便在不修改msg_split的情况下获取多个实例,以便索引保持不变?

2 个答案:

答案 0 :(得分:0)

通过修改我的函数来找到msg_split枚举的所有索引:

来修复它
def get_books(msg):
    results = []

    for key, value in books.items():
        for item in value:
            if item in msg:
                last_item = item.split(" ")[-1]
                msg_split = msg.split(" ")

                indices = [i for i, x in enumerate(msg_split) if x == last_item]

                for index in indices:
                    results.append((key, index))

    return results

答案 1 :(得分:0)

使用re

进行此操作
import re
alldata='yse sadsa se se'
item='se'
resultedarray=[]
for matcheditem in re.finditer(item,alldata):
        indexofs=matcheditem.start()
        resultedarray.append(indexofs)