2016-12-06 70 views
1
import MySQLdb 

db = MySQLdb.connect("localhost","root","password","database") 
cursor = db.cursor() 
cursor.execute("SELECT id FROM some_table") 
u_data = cursor.fetchall() 

>>> print u_data 
((1320088L,),) 

我找到了互聯網上讓我到這裏:的Python:轉換元組逗號分隔字符串

string = ((1320088L,),) 
string = ','.join(map(str, string)) 
>>> print string 
(1320088L,) 

我所期望的輸出看起來像:

#Single element expected result 
1320088L 
#comma separated list if more than 2 elements, below is an example 
1320088L,1320089L 

回答

3

使用itertools.chain_fromiterable()先彙整嵌套結構,然後map()字符串和join()。請注意,str()刪除了L後綴,因爲數據不再是long類型。

>>> from itertools import chain 
>>> s = ((1320088L,),) 
>>> ','.join(map(str,chain.from_iterable(s))) 
'1320088' 

>>> s = ((1320088L,1232121L),(1320088L,),) 
>>> ','.join(map(str,chain.from_iterable(s))) 
'1320088,1232121,1320088' 

注意,string是不是一個好變量名字,因爲它是一樣的string模塊。

3

我覺得string是包含長值的tupletuple

>>> string = ((1320088L,),) 
>>> ','.join(str(y) for x in string for y in x if len(x) > 0) 
'1320088' 
>>> 

例如,有多個值

>>> string = ((1320088L,1232121L),(1320088L,),) 
>>> ','.join(str(y) for x in string for y in x if len(x) > 0) 
'1320088,1232121,1320088' 
>>> 
+0

這個答案推廣以及與長度元組> 1. – sirfz

+0

不知道@Chris_Rands答案是一個更好的。這個答案和他的答案都適合我! – JackSparrow

+0

@JackSparrow這些天itertools是扁平化列表或元組的推薦方式http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python –

-1
string = ((1320088L,),) 
print(','.join(map(str, list(sum(string,()))))) 
string = ((1320088L, 1232121L), (1320088L,),) 
print(','.join(map(str, list(sum(string,()))))) 

輸出:

1320088 
1320088,1232121,1320088 
相關問題