Skip to main content
 首页 » 编程设计

python之提取一个 2 元素元组并将其转换为字符串

2025年05月04日25sky-heaven

所以我有一个这样的随机单词列表:

[('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 

有没有办法优雅地做到这一点?

请您参考如下方法:

使用列表理解来加入它们;使用 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']