我有一个元组列表,看起来像这样:
[('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')]
什么是最符合Python风格且高效的方法,将其转换为每个标记之间用空格分隔的格式?
['this is', 'is the', 'the first', 'first document', 'document .']
我有一个元组列表,看起来像这样:
[('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')]
['this is', 'is the', 'the first', 'first document', 'document .']
非常简单:
[ "%s %s" % x for x in l ]
[("%s "*len(x)%x).strip() for x in l]
。如果一个元组有3个条目或更多,它也能适用。请注意,翻译保持原意并尽可能保持技术准确性。 - Joran Beasley" ".join
即可。 - Julian[" ".join(x) for x in l]
。 - Joran Beasley' '.join
可以很好地解决这个问题。请看我的回答。 - Joel Cornett' '.join(tup)
是最好的方法。 - inspectorG4dget使用 map()
和 join()
:
tuple_list = [('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')]
string_list = map(' '.join, tuple_list)
string_list = [' '.join(item) for item in tuple_list]
我强烈建议你避免使用%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>>> 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']
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 .']
%s
,对于版本3.6+,它使用f-string,而对于早期版本,则使用str.format
。 - lmiguelvargasf