提取2element元组并将其转换为字符串

2024-05-14 08:24:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

有没有办法做到优雅?你知道吗


Tags: 列表thisnow元组was办法产物frenchy
3条回答

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

对于更大的iterables(和内存高效使用),您可能需要使用itertools模块中的一些东西,比如starmap函数:

import itertools

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

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

当然,这也是一种优雅的方式。你知道吗

使用列表压缩。解包字符串的每个元组并将字符串添加到一起。你知道吗

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

相关问题 更多 >

    热门问题