[Newbie] Strange output from list
Steve Holden
steve at holdenweb.com
Tue Nov 11 06:47:56 EST 2008
Chris Rebert wrote:
> On Tue, Nov 11, 2008 at 12:56 AM, Gilles Ganault <nospam at nospam.com> wrote:
>> On Mon, 10 Nov 2008 20:02:39 -0600, Andrew <alif016 at gmail.com> wrote:
>>> sql = 'SELECT id FROM master'
>>> rows=list(cursor.execute(sql))
>>> for id in rows:
>>> sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
>>> result = list(cursor.execute(sql))
>>> print "Code=%s, number=%s" % (id[0],result[0][0])
>
> Using liberal "term rewriting", consider the following rough
> equivalencies in the code:
>
> id[0] <==> rows[INDEX_HERE][0] <==> list(cursor.execute(sql))[INDEX_HERE][0]
> result[0][0] <==> list(cursor.execute(sql))[0][0]
>
> Note that in both cases, the list is sliced twice; the for-loop just
> conceals the `[INDEX_HERE]` implicit slicing that is caused by
> iterating over the list.
You might also want to consider saving some time by using a SQL solution
(assuming SQLite supports it, which it should) (untested):
cursor.execute("""
SELECT master.id, count(companies.code)
FROM master JOIN companies ON master.id = companies.code
GROUP BY companies.code""")
for id, count in cursor.fetchall():
print "Code=%s, number=%s" % (id, count)
I'd like to think it makes the Python a bit more readable too ...
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list