【问题标题】:How to join two words together in a list with a space in the middle?如何将两个单词连接到一个列表中,中间有一个空格?
【发布时间】:2022-11-07 22:22:20
【问题描述】:

我有一个这样的列表:

['which', 'means', 'which', 'one','which', 'will]

我怎么可能将两个词连接在一起并形成这个:

['which means', 'which one', 'which will']

【问题讨论】:

  • 一种可能性是使用join 字符串方法,另一种可能性是使用+ 字符串连接。

标签: python python-3.x


【解决方案1】:

这是使用joinzip 的选项:

>>> 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')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 2010-10-20
    • 2020-06-23
    • 1970-01-01
    • 2023-03-19
    • 2011-12-27
    • 1970-01-01
    相关资源
    最近更新 更多