im beginner with python.I want to convert sql results to a list.Here's my code:

我是初学者用python.I想将sql结果转换为list.Here是我的代码:

cursor = connnect_db()

query = "SELECT * FROM `tbl`"

cursor.execute(query)

options = list()

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

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

我的表中有6列但是这段代码没有创建6个元素列表。我做错了什么?

2 个解决方案

#1


20

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

如果你在Python中有一个iterable,要创建一个列表,可以简单地调用内置的list():

list(cursor.fetchall())

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

请注意,iterable通常与列表一样有用,并且可能更有效,因为它可能是惰性的。

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.

您的原始代码失败,因为它没有太多意义。你循环遍历行并枚举它们,所以得到(0,first_row),(1,second_row)等... - 这意味着你要构建每个第n行的第n项的列表,这不是你想要什么。

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.

此代码显示了一些问题 - 首先,没有任何参数的list()通常更好地替换为空列表文字([]),因为它更容易阅读。

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.

接下来,你试图按索引循环,这在Python中是一个坏主意。循环遍历值本身,而不是您用于获取值的索引。

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.

另请注意,当您确实需要构建这样的值列表时,列表推导是执行此操作的最佳方式,而不是创建列表,然后附加到列表。

更多相关文章

  1. python打印列表的下标和值的例子:
  2. 使用python如何在列表列表中找到元素,而关键元素是内部列表的元素
  3. Python学习记录--关于列表和字典的比较
  4. 支持c和python之间的跨语言(c)标记的代码编辑器
  5. 如何将两个列表中的数据写入csv中的列?
  6. 在python 3.3列表中查找最小值
  7. python基础练习--列表问题
  8. 【小白自学笔记】【机器学习实战】【Python代码逐行理解】CH02
  9. 如何用所有可能的方式将一个列表分割成对?

随机推荐

  1. K8s 平台可以如何处理 Pod 预授权问题
  2. 学习C的第三天-while语句
  3. 一篇文章看明白 Android(安卓)Service 启
  4. 【安卓】Content Provider 基础
  5. 一看就懂【来自英雄联盟盖伦的怒吼】与 P
  6. libp2p-rs kad 使用及调试方法
  7. 一看就懂,Python 日志模块详解及应用
  8. Python排序算法[二]:测试数据的迷雾散去
  9. 你还在用 os.path?快来感受一下 pathlib
  10. Python 系统资源信息获取工具,你用过没?