Need max values in list of tuples, based on position

Dennis Lee Bieber wlfraed at ix.netcom.com
Sat Nov 12 13:51:36 EST 2022


On Sat, 12 Nov 2022 13:24:37 -0500, Dennis Lee Bieber
<wlfraed at ix.netcom.com> declaimed the following:


>	Granted, this will NOT work with "select *" unless one does the select
>*/fetchall first, AND extracts the names from the cursor description --
>then run a loop to create the select max(length(col)), ... statement (which
>is why I state the fetchall step, as unless one creates a second cursor,
>the latter select will wipe out any unfetched data from the first).
>

	Okay, a follow-up...


>>> import sqlite3 as db
>>> con = db.connect("c:/users/wulfraed/documents/.localdatabases/solitaire-sqlite/solitaire.db")
>>> cur = con.cursor()
>>> cur.execute("select * from game")
<sqlite3.Cursor object at 0x0000022453703F80>
>>> columns = [ "max(length(%s))" % col[0] for col in cur.description ]
>>> columns
['max(length(ID))', 'max(length(Variant))', 'max(length(Num_of_Decks))',
'max(length(Cards_in_Deck))', 'max(length(Num_Tableau_Cards))',
'max(length(Num_Reserve_Cards))', 'max(length(Foundation_Value))',
'max(length(Tableau_Value))', 'max(length(Reserve_Value))']
>>> sql = "select %s from game" % ", ".join(columns)
>>> data = cur.fetchall()
>>> cur.execute(sql)
<sqlite3.Cursor object at 0x0000022453703F80>
>>> widths = cur.fetchone()
>>> widths
(1, 16, 1, 2, 2, 2, 1, 2, 2)
>>> pformat = [ f'%{w}s' for w in widths ]
>>> pformat
['%1s', '%16s', '%1s', '%2s', '%2s', '%2s', '%1s', '%2s', '%2s']
>>> pformat = " | ".join(pformat)
>>> for row in data:
... 	print(pformat % row)
... 
1 |  Klondike draw-3 | 1 | 52 | 28 | 24 | 1 | -1 | -2
2 | Perpetual Motion | 1 | 52 |  0 | 52 | 1 | -1 | -1
3 |  Klondike draw-1 | 1 | 52 | 28 | 24 | 1 | -1 | -2

	I used " | " rather than "\t" as column separators. View with a fixed
width font.

	It could be a tad shorter -- the list-comps for columns and widths
(pformat) could be embedded IN the .join() calls.


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


More information about the Python-list mailing list