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

8
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
3个回答

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


6
我认为这个 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'
>>>

1
这个答案适用于长度大于1的元组。 - sirfz
不确定@Chris_Rands的答案是否更好。这个答案和他的答案都对我有用! - karan_s438
@JackSparrow 这些天,itertools 是将列表或元组展平的推荐方法 https://dev59.com/qnNA5IYBdhLWcg3wdtld - Chris_Rands

-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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接