将SQL结果转换为列表Python [英] Convert sql result to list 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 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 This code shows some problems - firstly, 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屋!list()
built-in:list(cursor.fetchall())
(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.list()
without any arguments is generally better replaced with an empty list literal ([]
), as it's easier to read.