【问题标题】:Converting sqlite3 records to list将 sqlite3 记录转换为列表
【发布时间】:2018-10-09 05:24:32
【问题描述】:

我尝试使用下面的代码将sqlite3 记录转换为列表,但结果以这种方式输出

[[1000], [1199], [1400], [1213], [1500], [1800], [1308]]

使用下面的代码,但我希望结果显示为:

[1000, 1199, 1400, 1213, 1500, 1800, 1308]

list 中的数字中删除list

conn = sqlite3.connect("TEST1.db")
cur = conn.cursor()
cur.execute("SELECT POINT FROM loyalty")
rows = cur.fetchall()

result = [list(i) for i in rows]

print(result)

我试图以这种方式迭代结果

for row in rows:
    print(list(row))

它以这种方式输出

[1000]
[1199]
[1400]
[1213]
[1500]
[1800]
[1308]

【问题讨论】:

  • 尝试结果 = [i for i in rows]
  • 已经试过号码在tuple
  • 是的,抱歉结果 = [i[0] for i in rows]

标签: python list sqlite tuples


【解决方案1】:

fetchall 返回的每一行都是一个元组,SELECT 中的每个属性都有相应的索引,所以:

result = [i[0] for i in rows]

i[0] 将是 POINT 列。

或者试试迭代器形式:

for row in c.execute('SELECT POINT FROM loyalty'):
        print(row[0])

【讨论】:

    【解决方案2】:

    可以有多种方法来获得预期的结果。

    即使子列表的长度为奇数,以下方法也可以工作

    行 = [[1000]、[1199]、[1400]、[1213]、[1500]、[1800]、[1308]]

    最简单的方法

    endResult = []
    for item in rows:
        for subItem in item:
            endResult.append(subItem)
    print(endResult)
    

    输出:[1000、1199、1400、1213、1500、1800、1308]

    另一种解决方法

    import itertools
    rows = [[1,2,3],[4,5,6], [7], [8,9]]
    endResult = list(itertools.chain.from_iterable(rows))
    print(endResult)
    

    输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]

    使用列表属性之一(sum)

    endResult = sum(rows, [])
    print(endResult)
    

    输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]

    使用 lambda 表达式

    endResult = reduce(lambda x,y: x+y,rows)
    print(endResult)
    

    输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]

    【讨论】:

    • @O JOE 如果此解决方案帮助您获得预期结果,请接受答案
    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 2019-11-10
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    相关资源
    最近更新 更多