【问题标题】:How to write 3 lists to 6 columns with Python3 and SQlite3如何使用 Python 和 SQlite3 将 3 个列表写入 6 列
【发布时间】:2017-05-17 00:51:26
【问题描述】:

我需要使用 sqlite3 将 3 个包含值对的列表写入 6 列。

my_list = ['a','1','b','2','c','3','d','4']
my_list2 = ['e','5','f','6','g','7','h','8']
my_list3 = ['i','9','j','10','k','11','l','12']

像这样:

| a | 1 | e | 5 | i | 9 |
| b | 2 | f | 6 | j | 10|
| c | 3 | g | 7 | k | 11|
| d | 4 | h | 8 | l | 12|

我需要将每一对插入到彼此相邻的 .db 中。我可以使用成对函数来执行此操作,并为单个列表执行许多操作。

成对函数:

def pairwise(iterable):
    iterable = iter(iterable)
    return zip(iterable, iterable)

为一个列表执行多个代码:

cursor.executemany('INSERT INTO mytable(column1, column2) VALUES (?,?)', pairwise(my_list))
connection.commit()

每当我尝试同时通过其他列表时:

cursor.executemany('INSERT INTO mytable(column1, column2, column3, column4, column4, column6) VALUES (?,?,?,?,?,?)',pairwise(my_list),pairwise(my_list2),pairwise(my_list3))
conn.commit()

我收到一条错误消息:

TypeError: function takes exactly 2 arguments (4 given)

【问题讨论】:

    标签: database sqlite python-3.x executemany


    【解决方案1】:

    executemany() 可以将 an 序列迭代器(例如元组)作为参数,但是当您编写时

    pairwise(my_list),pairwise(my_list2),pairwise(my_list3)
    

    这为您提供了 三个 元组迭代器,而不是一个组合的元组迭代器。它不合并列。

    这是组合列的一种方法:

    def concat_columns(*row_lists):
        return (tuple(chain(*r)) for r in zip(*row_lists)
    

    这使用zip() 来创建元组的元组的迭代器,并使用itertools.chain() 来展平每一行。您的最终代码可能如下所示:

    cursor.executemany(
        'INSERT INTO mytable(column1, column2, column3, column4, column4, column6) VALUES (?,?,?,?,?,?)',
        concat_columns(pairwise(my_list),pairwise(my_list2),pairwise(my_list3)))
    

    【讨论】:

    • 由于某种原因,当我这样做时,错误不再存在,因为我的列出现空白,没有任何内容。
    • @ChaceMcguyer 哎呀,我误解了你的问题。我的回答不会奏效。感谢您的编辑澄清了您的意思。
    • @ChaceMcguyer 尤其是我的 cmets 关于用简单的 zip 替换 pairwise 是完全错误的。
    • 我收到一个错误,即 concat_columns 函数中未定义链
    • 是否需要用def chain(*iterables)之类的函数来定义链:
    猜你喜欢
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2012-01-02
    • 1970-01-01
    • 2021-05-27
    • 2016-01-06
    相关资源
    最近更新 更多