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

9

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

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

什么是最符合Python风格且高效的方法,将其转换为每个标记之间用空格分隔的格式?
['this is', 'is the', 'the first', 'first document', 'document .']

1
我已经添加了一个答案,避免使用%s,对于版本3.6+,它使用f-string,而对于早期版本,则使用str.format - lmiguelvargasf
5个回答

15

非常简单:

[ "%s %s" % x for x in l ]

3
在这个例子中,如果你不知道每个元组的长度,可以使用以下代码来解决:[("%s "*len(x)%x).strip() for x in l]。如果一个元组有3个条目或更多,它也能适用。请注意,翻译保持原意并尽可能保持技术准确性。 - Joran Beasley
@JoranBeasley 不需要,你只需要使用" ".join即可。 - Julian
@Julian,是的,你说得对...脑抽了[" ".join(x) for x in l] - Joran Beasley
@Julian:是的,我同意' '.join可以很好地解决这个问题。请看我的回答。 - Joel Cornett
2
这仅适用于2元组。对于较大的n元组,扩展此内容将会很困难。' '.join(tup) 是最好的方法。 - inspectorG4dget

9

使用 map()join():

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

string_list = map(' '.join, tuple_list) 

正如inspectorG4dget指出的那样,列表推导式是实现此操作的最Pythonic的方式:
string_list = [' '.join(item) for item in tuple_list]

2

我强烈建议你避免使用%s。从Python 3.6开始,添加了f-strings,因此您可以按照以下方式利用此功能:

[f'{" ".join(e)}' for e in l]

如果您正在使用Python 3.6的早期版本,您也可以通过以下方式使用format函数来避免使用%s

print(['{joined}'.format(joined=' '.join(e)) for e in l]) # before Python 3.6

替代方案:

假设每个元组中有2个元素,您可以使用以下方法:

# Python 3.6+
[f'{first} {second}' for first, second in l]

# Before Python 3.6
['{first} {second}'.format(first=first, second=second) for first, second in l]

[f’{} {}’ for *x in l] 更好 - Orbital
@Orbital,我更新了我的答案。你建议的方法不起作用,但我明白你希望我让答案更一般化。 - lmiguelvargasf
抱歉,我无法测试它。我以为它会工作。 - Orbital

2
这就做到了:
>>> l=[('this', 'is'), ('is', 'the'), ('the', 'first'), 
('first', 'document'), ('document', '.')]
>>> ['{} {}'.format(x,y) for x,y in l]
['this is', 'is the', 'the first', 'first document', 'document .']

如果你的元组是可变长度的(或者甚至不是元组),你也可以这样做:
>>> [('{} '*len(t)).format(*t).strip() for t in [('1',),('1','2'),('1','2','3')]]
['1', '1 2', '1 2 3']   #etc

或者,最好的选择可能是:
>>> [' '.join(t) for t in [('1',),('1','2'),('1','2','3'),('1','2','3','4')]]
['1', '1 2', '1 2 3', '1 2 3 4']

0
假设列表如下:
您可以使用列表推导式+join()
li = [('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')]

你需要做的就是:

[' '.join(x) for x in li]

你也可以使用 map() + join()

list(map(' '.join, li))

结果:

['this is', 'is the', 'the first', 'first document', 'document .']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接