2012-07-27 56 views
4

我有一个元组列表,看起来像这样的列表:的Python - 一个元组列表转换为字符串

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

什么是转换成这其中每个令牌分开的最Python的和有效的方法用一个空格:

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

回答

11

很简单:

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

或者,' “{0} {1}” 格式(* X)'' – 2012-07-27 21:52:09

+3

[( “%S” * LEN(X)%X).strip。 ()for x in l]'如果你不知道每个元组是多久...在这个例子中它的2 ...但是如果一个人有3个条目或someat这将占到这个 – 2012-07-27 21:52:33

+0

@JoranBeasley不,你只是为此使用'“”.join'。 – Julian 2012-07-27 21:54:15

7

使用map()join()

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

string_list = map(' '.join, tuple_list) 

由于inspectorG4dget指出,列表内涵都是这样做的最Python的方式:

string_list = [' '.join(item) for item in tuple_list] 
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']