gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:17 25 4
gpt4 key购买 nike

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.()???

最佳答案

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')

关于python - 如何使函数返回第一个字符串中出现的第二个字符串中的字符的索引列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40224680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com