为什么Python数据库查询会以这种方式返回记录集结果?

发布于 2024-08-30 15:46:31 字数 192 浏览 11 评论 0原文

我四处寻找答案,以了解为什么查询结果以这种格式返回以及如何转换为列表。

data =cursor.fetchall()

当我打印数据时,结果是: (('car',), ('boat',), ('plane',), ('truck',))

我希望将结果显示为 ["car", "boat", "plane “, “卡车”]

I have searched high and low for an answer to why query results returned in this format and how to convert to a list.

data = cursor.fetchall()

When I print data, it results in:
(('car',), ('boat',), ('plane',), ('truck',))

I want to have the results in a list as ["car", "boat", "plane", "truck"]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

左耳近心 2024-09-06 15:46:31

它以这种方式返回它,因为记录集由许多数据行组成,而不是单个元素的列表。

如果您想使用列表理解,您可以将其展平:

data = [row[0] for row in cursor.fetchall()]

It's returning it in that way because a recordset is comprised of many rows of data, not a list of single elements.

You can flatten it if you want using a list comprehension:

data = [row[0] for row in cursor.fetchall()]
话少心凉 2024-09-06 15:46:31

fetchall() 的结果返回一个行数组,其中每一行都是一个每列一个值的数组。

即使您只选择一列,您仍然会得到一组数组,但每一行只有一个值。

The result for fetchall() returns an array of rows, where each row is an array with one value per column.

Even if you are selecting only one column, you will still get an array of arrays, but only one value for each row.

简单气质女生网名 2024-09-06 15:46:31
x = (('car',), ('boat',), ('plane',), ('truck',))

y = [z[0] for z in x] # ['car', 'boat', 'plane', 'truck']
x = (('car',), ('boat',), ('plane',), ('truck',))

y = [z[0] for z in x] # ['car', 'boat', 'plane', 'truck']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文