2016-12-06 94 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