2016-04-23 87 views
1

所以我有這樣的隨機單詞的列表:提取2元元組並將其轉換爲字符串

[('Frenchy', 'INTENSE'), ('Frenchy', 'ComputerScienceFTW'), ('Frenchy', 'HelloMrGumby'), ('INTENSE', 'Frenchy'), ('INTENSE', 'ComputerScienceFTW'), ('INTENSE', 'HelloMrGumby'), ('ComputerScienceFTW', 'Frenchy'), ('ComputerScienceFTW', 'INTENSE'), ('ComputerScienceFTW', 'HelloMrGumby'), ('HelloMrGumby', 'Frenchy'), ('HelloMrGumby', 'INTENSE'), ('HelloMrGumby', 'ComputerScienceFTW')] 

是置換的產物。現在我有這個,我希望像這樣在元組中添加項目:

[('Frenchy', 'INTENSE')] # Was this 
'FrenchyINTENSE' # Now this 

有沒有辦法優雅地做到這一點?

回答

3

使用列表理解加入它們;這是最簡單的與str.join() method

[''.join(t) for t in list_of_tuples] 

,但你也可以使用開箱和直線上升的串聯:

[a + b for a, b in list_of_tuples] 

str.join()方法的優點是將任意長度的序列工作。

演示:

>>> list_of_tuples = [('Frenchy', 'INTENSE'), ('Frenchy', 'ComputerScienceFTW'), ('Frenchy', 'HelloMrGumby'), ('INTENSE', 'Frenchy'), ('INTENSE', 'ComputerScienceFTW'), ('INTENSE', 'HelloMrGumby'), ('ComputerScienceFTW', 'Frenchy'), ('ComputerScienceFTW', 'INTENSE'), ('ComputerScienceFTW', 'HelloMrGumby'), ('HelloMrGumby', 'Frenchy'), ('HelloMrGumby', 'INTENSE'), ('HelloMrGumby', 'ComputerScienceFTW')] 
>>> [''.join(t) for t in list_of_tuples] 
['FrenchyINTENSE', 'FrenchyComputerScienceFTW', 'FrenchyHelloMrGumby', 'INTENSEFrenchy', 'INTENSEComputerScienceFTW', 'INTENSEHelloMrGumby', 'ComputerScienceFTWFrenchy', 'ComputerScienceFTWINTENSE', 'ComputerScienceFTWHelloMrGumby', 'HelloMrGumbyFrenchy', 'HelloMrGumbyINTENSE', 'HelloMrGumbyComputerScienceFTW'] 
>>> [a + b for a, b in list_of_tuples] 
['FrenchyINTENSE', 'FrenchyComputerScienceFTW', 'FrenchyHelloMrGumby', 'INTENSEFrenchy', 'INTENSEComputerScienceFTW', 'INTENSEHelloMrGumby', 'ComputerScienceFTWFrenchy', 'ComputerScienceFTWINTENSE', 'ComputerScienceFTWHelloMrGumby', 'HelloMrGumbyFrenchy', 'HelloMrGumbyINTENSE', 'HelloMrGumbyComputerScienceFTW'] 
2

使用列表複製。解壓每個字符串元組並將字符串添加到一起。

>>> lst = [('Frenchy', 'INTENSE'), ('Frenchy', 'ComputerScienceFTW')] 
>>> [a+b for a,b in lst] 
['FrenchyINTENSE', 'FrenchyComputerScienceFTW'] 
2

對於較大iterables(和內存有效使用),你也許想用的東西從itertools模塊裏,像starmap功能:

import itertools 

tuples = [('Frenchy', 'INTENSE'), ('Frenchy', 'ComputerScienceFTW'),] 

result = itertools.starmap(lambda a, b: a + b, tuples) 

,當然還有,這是一個優雅的方式去。