2

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)

1 つのリストに対して機能する多くのコードを実行します。

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)
4

1 に答える 1

0

executemany()引数にシーケンス (タプルなど)のイテレータを取ることができますが、

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

これにより、タプルの 1 つの結合イテレーターではなく、タプルの3 つのイテレーターが得られます。列を結合しません。

列を結合する 1 つの方法を次に示します。

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)))
于 2017-01-03T03:04:27.827 に答える