如何使一个函数返回第二个字符串中出现在第一个字符串中的字符索引列表?

2024-04-20 02:03:09 发布

您现在位置:Python中文网/ 问答频道 /正文

def get_indices_from_the_second_string(string1, string2):
    '''(str, str) -> list of int
    >>> get_indices_from_the_second_string('AGTACACGTTAC', 'GAATTC')
    [1, 3, 5, 8, 9, 11]
    >>> get_indices_from_the_second_string('AGTACACGTTAC', 'GGATCC')
    [1, 7, 10]
    '''

    acc= []

    for i in range(0, len(string2)):
        for r in range(0, len(string1)):
            if len(acc) == len(string2):
                            break            
            if string1[r] == string2[i]:
                acc.append(r)
                i += 1
                r += 1
    return acc

    # the second example is wrong
    # how to make it not reversed only from left to right
    # maybe use find.()???

Tags: theinfromforgetstringlenrange
3条回答
def get_indices_from_the_second_string(string1, string2):
    acc = []
    s2_counter = 0
    for i, letter in enumerate(string1):
        if letter == string2[s2_counter]:
            acc.append(i)
            s2_counter += 1
            if len(acc) == len(string2):
                break
    return acc

a = get_indices_from_the_second_string('GAATTCCGTTAC', 'GAATTC')

哦,我知道你在做什么了。你知道吗

def get_indices_from_the_second_string(string1, string2):
    acc = []
    string1_index = 0
    for char in string2:
        while string1[string1_index] != char:
            string1_index += 1
            if string1_index >= len(string1):
                return acc
        acc.append(string1_index)
        string1_index += 1
        if string1_index >= len(string1):
            return acc
    return acc

删除行

            i += 1
            r += 1

for循环自动增加ir。你知道吗

然后修改代码:

lower = 0                             # from this index will be string1 searched

for i in range(0, len(string2)):
    for r in range(lower, len(string1)):
        if string1[r] == string2[i]:
            acc.append(r)
            lower = r + 1             # indexes from 0 to r are already used
            break
        elif r == len(string1) - 1:   # last index did not match
            return acc
return acc

相关问题 更多 >