python - How to put lists together into list holding them as 'tuples' -


in pythons sqlite documents have following example on how put many values sql database:

purchases = [('2006-03-28', 'buy', 'ibm', 1000, 45.00),              ('2006-04-05', 'buy', 'msft', 1000, 72.00),              ('2006-04-06', 'sell', 'ibm', 500, 53.00),             ] c.executemany('insert stocks values (?,?,?,?,?)', purchases)  

but if have 1 list containing dates, 1 containing buy/sell, 1 containing stock tickers, 1 amount , 1 price, how combine them @ optimal way, before insert? i've tried looping on each list , inserting them in sqlite db 1 one, takes time.

dates = ['2006-03-28', '2006-04-05', '2006-04-06'] flags = ['buy', 'buy', 'sell'] tickers = ['ibm', 'msft', 'ibm'] amount = [1000, 1000, 500] price = [45.00, 72.00, 53.00] 

this takes long:

for in range(0, len(dates)):      c.executemany('insert stocks values (?,?,?,?,?)', dates[i], flags[i], tickers[i], amount[i], price[i]) 

you can use zip() function transpose input lists suitable executemany():

rows = zip(dates, flags, tickers, amount, price) c.executemany('insert stocks values (?,?,?,?,?)', rows) 

the function pairs elements each list new tuple; each first element 1 tuple, each second element second, etc.

demo:

>>> pprint import pprint >>> dates = ['2006-03-28', '2006-04-05', '2006-04-06'] >>> flags = ['buy', 'buy', 'sell'] >>> tickers = ['ibm', 'msft', 'ibm'] >>> amount = [1000, 1000, 500] >>> price = [45.00, 72.00, 53.00] >>> rows = zip(dates, flags, tickers, amount, price) >>> pprint(rows) [('2006-03-28', 'buy', 'ibm', 1000, 45.0),  ('2006-04-05', 'buy', 'msft', 1000, 72.0),  ('2006-04-06', 'sell', 'ibm', 500, 53.0)] >>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> conn.execute(''' ... create table stocks ( ...     date datetime, ...     action string, ...     symbol string, ...     quantity integer, ...     price real) ... ''') <sqlite3.cursor object @ 0x10667bc70> >>> cursor = conn.cursor() >>> cursor.executemany('insert stocks values (?,?,?,?,?)', rows) <sqlite3.cursor object @ 0x10667bce0> >>> conn.commit() >>> row in cursor.execute('select * stocks'): ...     print(row) ...  (u'2006-03-28', u'buy', u'ibm', 1000, 45.0) (u'2006-04-05', u'buy', u'msft', 1000, 72.0) (u'2006-04-06', u'sell', u'ibm', 500, 53.0) 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -