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

时间:2012-03-09 00:37:30

标签: python

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

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

5 个答案:

答案 0 :(得分:5)

几乎在那里,这将有效:

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

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

答案 1 :(得分:0)

怎么样:

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

#output
'hello yo'

或者如果你不想要空格:

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

#output
'helloyo'

答案 2 :(得分:0)

除了xxx.joinxxx作为分隔符加入join之外,你所拥有的内容几乎可以正常工作,并且由于'helloyo'是一个函数,它需要围绕它的括号。

所以如果你想要''.join([tuple[0] for tuple in tuples]) ,那就做:

join

事实上,对于''.join(tuple[0] for tuple in tuples) ,您甚至不需要列表理解:

{{1}}

答案 3 :(得分:0)

你很近,但是join是一个函数,所以你需要(),而不是[]

答案 4 :(得分:0)

join是一种方法,如果是字符串。您使用的是[],您需要''.join()