Afternoon, i am trying to retrieve seat numbers from a database using the following code
cur.execute("SELECT * FROM seats")
while True:
row = cur.fetchone()
if row == None:
break
print row[0]
But when i do so, it prints out each individual record one per line like so :
A1
A2
B3 etc..
But i want each row to print out with the same letter if that makes sense such as :
A1 A2 A3 A4 A5 A6 A7 A8
B1 B2 B3 B4 B5 B6 B7
But i cant seem to get it like that ? How would i go about doing this?
Use the
itertools.groupby()tool:The
groupby()function loops over each row incur, take the first letter of the first column, and give you a tuples with each(letter, rows)values. Therowsvalue is another iterable, you can loop over that (with aforloop, for example) to list all rows that have that first letter.This does rely on the rows being sorted already. If your rows alternate between first letters:
it’ll print those as separate groups:
You may want to add a
ORDER BY firstcolumnnameordering instruction to your query to ensure correct grouping.This is what I see when I create a test db: