有一个带字符串的元组列表,想在Python中变成一个字符串吗

2024-09-29 06:25:46 发布

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

我有一个看起来像[("hello", 12), ("yo", 30)]的数据结构。如何将每个元组的第0个位置合并成一个字符串?上面的输出如下:"helloyo"。 以下是我尝试过的:

' '.join[tuple[0] for tuple in tuples]

Tags: 字符串in数据结构hellofor元组joinyo
3条回答

怎么样:

d = [("hello", 12), ("yo", 30)]
' '.join( [ t[ 0 ] for t in d ] )

#output
'hello yo'

或者如果你不想要空间:

^{pr2}$

就在那里,这将起作用:

''.join(t[0] for t in tuples)

顺便说一句,不要使用tuple作为变量,因为它也是python类型。在

你所得到的几乎可以工作,除了xxx.joinxxx作为分隔符连接参数,并且由于join是一个函数,它需要在它周围加上括号。在

所以如果你想'helloyo',只需:

''.join([tuple[0] for tuple in tuples])

实际上,对于join,您甚至不需要列表理解:

^{pr2}$

相关问题 更多 >