Jac*_*row 4 python mysql string tuples python-2.x
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,),)
Run Code Online (Sandbox Code Playgroud)
我在互联网上找到的东西让我直到这里:
string = ((1320088L,),)
string = ','.join(map(str, string))
>>> print string
(1320088L,)
Run Code Online (Sandbox Code Playgroud)
我期望输出看起来像:
#Single element expected result
1320088L
#comma separated list if more than 2 elements, below is an example
1320088L,1320089L
Run Code Online (Sandbox Code Playgroud)
我想string是tuple的tuple含长值。
>>> string = ((1320088L,),)
>>> ','.join(str(y) for x in string for y in x if len(x) > 0)
'1320088'
>>>
Run Code Online (Sandbox Code Playgroud)
例如具有多个值
>>> string = ((1320088L,1232121L),(1320088L,),)
>>> ','.join(str(y) for x in string for y in x if len(x) > 0)
'1320088,1232121,1320088'
>>>
Run Code Online (Sandbox Code Playgroud)
用于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'
Run Code Online (Sandbox Code Playgroud)
注意,string它不是一个好的变量名,因为它与string模块相同.