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

发布于 2021-01-29 16:34:39

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
关注者
0
被浏览
220
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    使用itertools.chain_fromiterable()先展平嵌套的元组,然后再map()字符串和join()。注意,str()删除L后缀是因为数据不再是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模块相同。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看