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

标签 python string python-3.x 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')]

这是排列的产物。现在我有了这个,我希望像这样将元组中的项目添加在一起:

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

关于python - 提取一个 2 元素元组并将其转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36811479/

相关文章:

python - 如何在 SQLAlchemy 中实现关注/关注者关系

java - 将 xml 字符串转换为 Java 对象

java - String.join() 与其他字符串连接操作

python - 如何将 OrderedDict 的混合列表转换为 Dataframe?

python - Elasticsearch analytics()与Python中的Spark不兼容?

python - Python中的Web Scraping表数据

php str_replace 是用什么字符串匹配算法写的?

None 类型或 dict 的类成员的 Python 类型提示

python - 在字典中使用整数类型键的字符串格式在 Python 2 中返回 KeyError,适用于字符串类型键

Python 参数解析 : diiference between -o and --option