Get a list of field values from Python's sqlite3, not tuples representing rows

后端 未结 8 963
我在风中等你
我在风中等你 2020-12-12 17:31

It\'s annoying how Python\'s sqlite3 module always returns a list of tuples! When I am querying a single column, I would prefer to get a plain list.

e.g. when I exec

相关标签:
8条回答
  • 2020-12-12 17:51
    zlist = []
    
    tupls = c.fetchall()
    
    for tup in tupls:
    
        t = str(tup).replace("('","").replace("',)","")
    
        zlist.append(t)
    

    Now you don't have to deal with tuples, pandas or any of the above that didn't work.

    0 讨论(0)
  • 2020-12-12 17:58
    data=cursor.fetchall()
    COLUMN = 0
    column=[elt[COLUMN] for elt in data]
    

    (My previous suggestion, column=zip(*data)[COLUMN], raises an IndexError if data is an empty tuple. In contrast, the list comprehension above just creates an empty list. Depending on your situation, raising an IndexError may be preferable, but I'll leave that to you to decide.)

    0 讨论(0)
提交回复
热议问题