-1

我有一个字符串列表,['what', 'is', 'apple', '&', 'orange'] 仅当 '&' 位于两个字符串之间时才想进行连接。通缉: ['what', 'is', 'apple&orange']

到目前为止我能想到的看起来很愚蠢有没有 Pythonic 的方法来做到这一点?

4

2 回答 2

3
l = ['what', 'is', 'apple', '&', 'orange', 'apple', '&', 'banana']

new_list = ' '.join(l).replace(' & ', '&').split()

# print(new_list)
['what', 'is', 'apple&orange', 'apple&banana']
于 2020-07-09T21:00:30.207 回答
0

这不是很pythonic,但它是我能想到的最干净的方式。请注意,如果您在列表的最后位置有一个“&”,则此代码会中断。

your_list = ['what', 'is', 'apple', '&', 'orange']

out = []
i = 0

while i < len(your_list):
    word = your_list[i]
    
    if (i < len(your_list) - 1) and your_list[i + 1] == '&':
         word = word + '&' + your_list[i + 2]
         i += 2
    
    out.append(word)
    i += 1

print(out)
于 2020-07-09T20:33:57.140 回答