将SQL结果转换为列表Python [英] Convert sql result to list python

查看:666
本文介绍了将SQL结果转换为列表Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python初学者.我想将sql结果转换为列表.这是我的代码:

cursor = connnect_db()

query = "SELECT * FROM `tbl`"

cursor.execute(query)

options = list()

for i,row in enumerate(cursor.fetchall()):
   options.append(row[i])

我的表中有6列,但是此代码不会创建6元素列表.我在哪里做错了?

解决方案

如果您在Python中具有可迭代性,可以列出一个列表,只需调用

There is 6 column in my table but this code doesn't create 6 element-list.Where am i doing wrong?

If you have an iterable in Python, to make a list, one can simply call the list() built-in:

list(cursor.fetchall())

Note that an iterable is often just as useful as a list, and potentially more efficient as it can be lazy.

Your original code fails as it doesn't make too much sense. You loop over the rows and enumerate them, so you get (0, first_row), (1, second_row), etc... - this means you are building up a list of the nth item of each nth row, which isn't what you wanted at all.

This code shows some problems - firstly, list() without any arguments is generally better replaced with an empty list literal ([]), as it's easier to read.

Next, you are trying to loop by index, this is a bad idea in Python. Loop over values, themselves, not indices you then use to get values.

Also note that when you do need to build a list of values like this, a list comprehension is the best way to do it, rather than creating a list, then appending to it.

这篇关于将SQL结果转换为列表Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆