gpt4 book ai didi

python - 如果满足条件,则将连续的字符串对连接到列表中

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

给定两个列表:

list1 = ["a","b","c","d","e","f","b","c","b","d","f","c","b","e"]
list2 = ["b","c"]

假设 len(list2) == 2,

我想知道如何获得这样的输出:

['a', 'bc', 'd', 'e', 'f', 'bc', 'b', 'd', 'f', 'c', 'b', 'e']

基本上 list1 中的 list2 的任何实例(按该顺序)应该连接到原始 list1 和输出中(在检查所有可能性之后)。

到目前为止我尝试了什么:

l = len(list1)

for i in range(0,l-1):
if list1[i] == list2[0]:
if list1[i+1] == list2[1]:
a = i
b = i+1
list1[a:b+1] = [''.join(list1[a:b+1])]
l = l - 1
print(list1)

但是一直报错:

if list1[i] == list2[0]: IndexError: list index out of range

最佳答案

试试这个,应该适用于任何长度的 list2 :

split_pattern = ''.join(list2)
chunks = ''.join(list1).split(split_pattern)

result = list(chunks[0])
for c in chunks[1:] :
result.append( split_pattern )
result.extend( list(c) )

检查结果:

>>> result
['a', 'bc', 'd', 'e', 'f', 'bc', 'b', 'd', 'f', 'c', 'b', 'e']

关于python - 如果满足条件,则将连续的字符串对连接到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56683534/

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