Python:将元组转换为逗号分隔的字符串

Python: Convert tuple to comma separated String

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,),)

我在网上找到的东西让我走到了这里:

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

我认为 stringtupletuple 包含长值。

>>> 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'
>>>

首先使用 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 模块相同。

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

输出:

1320088
1320088,1232121,1320088