gpt4 book ai didi

python - 在拆分字符串列表中查找字符串

转载 作者:太空狗 更新时间:2023-10-30 02:51:29 24 4
gpt4 key购买 nike

我有一个字符串 teststring 和一个子字符串列表 s 但是 teststring 被意外拆分了。现在我想知道列表中的索引,如果将它们放在一起,将重新创建 teststring

teststring = "Hi this is a test!"

s = ["Hi", "this is", "Hello,", "Hi", "this is", "a test!", "How are", "you?"]

预期的输出将是(构成 teststring 的列表 s 中的字符串需要连续出现 -> [0,4,5 ] 是错误的):

[3,4,5]

有人知道怎么做吗?

试图想出一个不错的解决方案,但没有发现任何有效的...

我只是记录了 teststring 的一部分出现在 s 中的一个子字符串中的每个实例:

test_list = []
for si in s:
if si in teststring:
flag = True

else:
flag = False
test_list.append(flag)

然后你会得到:[True, True, False, True, True, True, False, False]...然后必须采用最长的连续“True”的索引。任何人都知道如何获取这些索引?

最佳答案

如果您想要的是连接时形成字符串的连续索引列表,我认为这将满足您的需求:

teststring = "Hi this is a test!"

s = ["Hi", "this is", "Hello,", "Hi", "this is", "a test!", "How are", "you?"]

test_list = []
i = 0 # the index of the current element si
for si in s:
if si in teststring:
# add the index to the list
test_list.append(i)

# check to see if the concatenation of the elements at these
# indices form the string. if so, this is the list we want, so exit the loop
if ' '.join(str(s[t]) for t in test_list) == teststring:
break
else:
# if we've hit a substring not in our teststring, clear the list because
# we only want consecutive indices
test_list = []

i += 1

关于python - 在拆分字符串列表中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55698058/

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