我有一个包含大量单词的列表: 句子 = ['a','list','with','a','lot','of','strings','in','it']
我希望能够浏览列表并根据我所拥有的某些条件组合单词对。例如
['a','list','with','a','lot','of','strings','in','it'] 变成 ['列表','with','很多','of','字符串','in','it']
我尝试过类似的方法:
for w in range(len(sentence)):
if sentence[w] == 'a':
sentence[w:w+2]=[' '.join(sentence[w:w+2])]
但它不起作用,因为连接字符串会减小列表的大小并导致索引超出范围。有没有办法用迭代器和 .next() 或其他东西来做到这一点?
最佳答案
您可以使用迭代器。
>>> it = iter(['a','list','with','a','lot','of','strings','in','it'])
>>> [i if i != 'a' else i+' '+next(it) for i in it]
['a list', 'with', 'a lot', 'of', 'strings', 'in', 'it']
关于python - 将字符串连接到列表中的下一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6892472/