2024-09-29 06:25:46 发布
网友
我有一个看起来像[("hello", 12), ("yo", 30)]的数据结构。如何将每个元组的第0个位置合并成一个字符串?上面的输出如下:"helloyo"。 以下是我尝试过的:
[("hello", 12), ("yo", 30)]
"helloyo"
' '.join[tuple[0] for tuple in tuples]
怎么样:
d = [("hello", 12), ("yo", 30)] ' '.join( [ t[ 0 ] for t in d ] ) #output 'hello yo'
或者如果你不想要空间:
就在那里,这将起作用:
''.join(t[0] for t in tuples)
顺便说一句,不要使用tuple作为变量,因为它也是python类型。在
tuple
你所得到的几乎可以工作,除了xxx.join用xxx作为分隔符连接参数,并且由于join是一个函数,它需要在它周围加上括号。在
xxx.join
xxx
join
所以如果你想'helloyo',只需:
'helloyo'
''.join([tuple[0] for tuple in tuples])
实际上,对于join,您甚至不需要列表理解:
怎么样:
或者如果你不想要空间:
^{pr2}$就在那里,这将起作用:
顺便说一句,不要使用
tuple
作为变量,因为它也是python类型。在你所得到的几乎可以工作,除了
xxx.join
用xxx
作为分隔符连接参数,并且由于join
是一个函数,它需要在它周围加上括号。在所以如果你想
'helloyo'
,只需:实际上,对于
^{pr2}$join
,您甚至不需要列表理解:相关问题 更多 >
编程相关推荐