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

后端 未结 8 980
我在风中等你
我在风中等你 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:42

    I started with the following which gave me the same sort of list of tuples:

    video_ids = []
    
    for row in c.execute('SELECT id FROM videos_metadata'):
            video_ids.append(row)
    

    ...and so to resolve it and get the list I expected I just explicitly pulled out the first element within the returned tuple...

    video_ids = []
    
    for row in c.execute('SELECT id FROM videos_metadata'):
            video_ids.append(row[0])
    

    This seems to do the trick for me with a single column (per the OP's question) and is quite a simple solution (maybe it's simplistic in some way I've not thought of). Not sure how it scales but runs fast enough to deal with the 5000+ entries I have without caring too much (31ms), we're talking SQLite here so presumably this isn't going to be dealing with bazillions of rows.

提交回复
热议问题