猿问

如何仅在特定索引处加入字符串列表

我试图仅在 Python 中的特定索引处将字符串列表中的特定字符串连接在一起。想象一下你有清单

['foo', 'bar', 'baz', 'qux', 'quux']

我想最终得到以下列表:

['foo', 'bar baz', 'qux', 'quux']

鉴于字符串列表包含字符串baz

解决此问题的最有效方法是什么?


跃然一笑
浏览 190回答 3
3回答

素胚勾勒不出你

index = 2ss = ['foo','bar','far','car','sar']ss[index] = ' '.join(ss[index:index+2])ss.pop(index+1)print(ss)我希望这可行,因为它不需要创建新列表

慕田峪7331174

i = 0while i < len(s):&nbsp; &nbsp; print(s[i])&nbsp; &nbsp; if s[i] == 'baz' and i != 0:&nbsp; &nbsp; &nbsp; &nbsp; s[i - 1] += ' '&nbsp; &nbsp; &nbsp; &nbsp; s[i - 1] += ''.join(s[i])&nbsp; &nbsp; &nbsp; &nbsp; s.pop(i)&nbsp; &nbsp; &nbsp; &nbsp; i = i - 1&nbsp; &nbsp; i = i + 1上面的代码遍历列表,在找到 'baz' 的地方,它将 'baz' 连接到前面的元素。这无法使用 for 循环、 byfor i in s或来实现for i in range(len(s))。在代码中,由于 s.pop() 导致 len(s) 发生变化,因此i = i - 1是必要的,但for i in range(len(s))不允许更改 i 的值,因为它固定为从 0 变为 len(s)。对于为什么不使用 for 循环有任何疑问,请考虑以下代码:-for i in range(len(s)):&nbsp; &nbsp; print(s[i])&nbsp; &nbsp; if s[i] == 'baz':&nbsp; &nbsp; &nbsp; &nbsp; s.pop(i)&nbsp; &nbsp; i = i - 1这输出foobarbazquux---------------------------------------------------------------------------IndexError&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Traceback (most recent call last)<ipython-input-223-8034ffc6ca03> in <module>()&nbsp; &nbsp; &nbsp; 1 for i in range(len(s)):----> 2&nbsp; &nbsp; &nbsp;print(s[i])&nbsp; &nbsp; &nbsp; 3&nbsp; &nbsp; &nbsp;if s[i] == 'baz':&nbsp; &nbsp; &nbsp; 4&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s.pop(i)&nbsp; &nbsp; &nbsp; 5&nbsp; &nbsp; &nbsp;i = i - 1IndexError: list index out of range可以看出,它并没有遍历所有元素。由于 s.pop(),len(s) 减少到 4,s[3] 变成了 'quux',而不是 'qux'。尽管 i 存在i - 1,但它会引发错误。因此,while循环解决了这个问题。

神不在的星期二

你可以试试这个:>>> l = ['foo', 'bar', 'baz', 'qux', 'quux']>>> index = 2>>> l[index - 1] = f'{l[index-1]} {l.pop(index)}'>>> l['foo', 'bar baz', 'qux', 'quux']定时:382 ns ± 0.455 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
随时随地看视频慕课网APP

相关分类

Python
我要回答