我有一個元組列表,看起來像這樣的列表:的Python - 一個元組列表轉換爲字符串
[('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')]
什麼是轉換成這其中每個令牌分開的最Python的和有效的方法用一個空格:
['this is', 'is the', 'the first', 'first document', 'document .']
我有一個元組列表,看起來像這樣的列表:的Python - 一個元組列表轉換爲字符串
[('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')]
什麼是轉換成這其中每個令牌分開的最Python的和有效的方法用一個空格:
['this is', 'is the', 'the first', 'first document', 'document .']
很簡單:
[ "%s %s" % x for x in l ]
使用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]
該做的:
>>> 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} {1}」 格式(* X)'' – 2012-07-27 21:52:09
[( 「%S」 * LEN(X)%X).strip。 ()for x in l]'如果你不知道每個元組是多久...在這個例子中它的2 ...但是如果一個人有3個條目或someat這將佔到這個 – 2012-07-27 21:52:33
@JoranBeasley不,你只是爲此使用'「」.join'。 – Julian 2012-07-27 21:54:15