我有一個看起來像[("hello", 12), ("yo", 30)]
的數據結構。如何將每個元組的所有第0個位置合併爲一個字符串?上述輸出將如下所示:"helloyo"
。 以下是我已經試過:有一個帶字符串的元組列表,想在Python中變成單個字符串
' '.join[tuple[0] for tuple in tuples]
我有一個看起來像[("hello", 12), ("yo", 30)]
的數據結構。如何將每個元組的所有第0個位置合併爲一個字符串?上述輸出將如下所示:"helloyo"
。 以下是我已經試過:有一個帶字符串的元組列表,想在Python中變成單個字符串
' '.join[tuple[0] for tuple in tuples]
快到了,這將工作:
''.join(t[0] for t in tuples)
BTW,不要使用tuple
作爲變量,因爲它也是一個Python類型。
如何:
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'
你有什麼工作差不多,除了xxx.join
以xxx
作爲分隔符連接參數,並且因爲join
是一個函數,所以它需要括號。
所以,如果你想'helloyo'
,只是做:
''.join([tuple[0] for tuple in tuples])
事實上,對於join
,你甚至不需要列表理解:
''.join(tuple[0] for tuple in tuples)
你是接近,但join
是一個函數,所以你需要(),而不是[]
join
是一個方法,如果字符串。你正在使用[]
,你想要''.join()
。
'''.join'而不是'''.join'? – 2012-03-09 00:41:42