【问题标题】:How can I fetch mysql single column list results directly into a list in python?如何将mysql单列列表结果直接提取到python中的列表中?
【发布时间】:2013-07-11 14:40:56
【问题描述】:

我有一个mysql调用:

zip = 48326

cursor.execute ("""
    select distinct(name) 
      from usertab 
     where zip= %s
""" , (zip))

result = cursor.fetchall()

结果以如下所示的元组返回:

result = (('alan',), ('bob',), ('steve',), ('tom',))

但我需要这样的列表:

mylist= ['alan', 'bob', 'steve', 'tom']

所以我将元组处理成这样的列表:

mylist = []

for row, key in enumerate(result):
    for col, data in enumerate(key):
        mylist.append(data)

此代码有效,但我想要一种更简单的方法。
如何将 mysql 单列结果直接提取到列表中?

【问题讨论】:

  • 感谢 Tadeck 和 Pawelmhm... 我将我的 mysql 提取压缩为:mylist = [row[0] for row in cursor.fetchall()]

标签: python mysql list tuples


【解决方案1】:

这样做,使用list comprehension

mylist = [row[0] for row in result]

它将展平您的结果并从中创建列表。

另一种方法,没有列表理解:

from itertools import chain
mylist = list(chain.from_iterable(result))

它会将结果展平并将其转换为列表。

【讨论】:

    【解决方案2】:

    StackOverflow 上 75% 的 Python 问题可以用以下词回答:“列表理解”;)

    这是使用列表组合的解决方案:

    >>> result = (('alan',), ('bob',), ('steve',), ('tom',))
    >>> mylist = [i[0] for i in result]
    >>> mylist 
    ['alan', 'bob', 'steve', 'tom']
    

    请详细了解列表理解here,它将为您节省大量时间。

    【讨论】:

    • First ;) "StackOverflow 上 75% 的 Python 问题可以用以下词回答:"list comprehension";)" - 你有这方面的资料吗?跨度>
    • 好吧,我没有资源 :) 但是确实有很多问题可以通过列表理解来解决,这个工具真的很强大,很多人都不知道它。
    • 嗯,其实列表推导只是一个捷径。
    猜你喜欢
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多