python - 将字符串连接到列表中的下一个字符串

标签 python

我有一个包含大量单词的列表: 句子 = ['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/

相关文章:

python - 是否可以从 setuptools setup.py 中要求 PyQt?

python - Pypi:不允许存储或编辑包信息

python - 如何记录 Python 崩溃?

python - 在Python中总结小时和分钟的列

python - Conda 环境和 .BAT 文件

Python Pandas df.min() 返回 inf

python - 如何显示 PyQt 模式对话框并在关闭后从其控件中获取数据?

python - IRC 机器人无法连接到服务器 - Python

python - C DLL 到 Python 回调

python - 在 tensorflow 中连接 vgg19 的问题