【发布时间】:2022-11-07 22:22:20
【问题描述】:
我有一个这样的列表:
['which', 'means', 'which', 'one','which', 'will]
我怎么可能将两个词连接在一起并形成这个:
['which means', 'which one', 'which will']
【问题讨论】:
-
一种可能性是使用
join字符串方法,另一种可能性是使用+字符串连接。
标签: python python-3.x
我有一个这样的列表:
['which', 'means', 'which', 'one','which', 'will]
我怎么可能将两个词连接在一起并形成这个:
['which means', 'which one', 'which will']
【问题讨论】:
join 字符串方法,另一种可能性是使用+ 字符串连接。
标签: python python-3.x
这是使用join 和zip 的选项:
>>> words = ['which', 'means', 'which', 'one', 'which', 'will']
>>> [' '.join(z) for z in zip(words[::2], words[1::2])]
['which means', 'which one', 'which will']
稍微分解一下以显示切片操作 [::2] 的作用以及 zip 的作用:
>>> words[::2], words[1::2]
(['which', 'which', 'which'], ['means', 'one', 'will'])
>>> list(zip(words[::2], words[1::2]))
[('which', 'means'), ('which', 'one'), ('which', 'will')]
【讨论】: