Python - 将元组列表转换为字符串列表

Tam*_*mpa 8 python

我有一个看起来像这样的元组列表:

[('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')]
Run Code Online (Sandbox Code Playgroud)

什么是最pythonic和有效的方式转换为每个令牌由空格分隔:

['this is', 'is the', 'the first', 'first document', 'document .']
Run Code Online (Sandbox Code Playgroud)

Igo*_*bin 13

非常简单:

[ "%s %s" % x for x in l ]
Run Code Online (Sandbox Code Playgroud)

  • `[("%s"*len(x)%x).strip()for x in l]`如果你不知道每个元组有多长......在例子中它是2 ...但如果有3个条目或某些内容可以解释这一点 (3认同)
  • 这仅适用于2元组.对于大n来说,将它扩展到n元组是很困难的.`''.join(tup)`是最好的方法 (2认同)

Joe*_*ett 8

使用map()join():

tuple_list = [('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')]

string_list = map(' '.join, tuple_list) 
Run Code Online (Sandbox Code Playgroud)

正如inspectorG4dget指出的那样,列表推导是这样做的最pythonic方式:

string_list = [' '.join(item) for item in tuple_list]
Run Code Online (Sandbox Code Playgroud)