Python:将元组转换为逗号分隔的字符串 [英] Python: Convert tuple to comma separated String
本文介绍了Python:将元组转换为逗号分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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,),)
我在互联网上找到的东西让我到这里为止:
What I found on internet got me till here:
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
推荐答案
首先使用itertools.chain_fromiterable()
展平嵌套的元组,然后使用map()
展平字符串和join()
.请注意,str()
删除了L
后缀,因为数据不再是long
类型.
Use itertools.chain_fromiterable()
to flatten your nested tuples first, then map()
to string and join()
. Note that str()
removes the L
suffix because the data is no longer of type 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
模块.
Note, string
is not a good variable name because it is the same as the string
module.
这篇关于Python:将元组转换为逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文