Python List Comprehensions Part 1 of Many

One of the things you’re supposed to learn quickly about Python, at least as I understand it, is to not to code loops like this (please forgive indentation inconsistencies)

(loadAmrCsRow is a function that prepares a row for insert.)

for row in in_cur:

if not row[i.meter_num].isdigit():

continue

if 0 >= row[i.endpointid]:

continue

if 0 >= row[i.meter_num]:

continue

out_row = loadAmrCsRow(row, this_day)

print(out_row)

.

.

.

but instead reformat them like this, using list comprehensions.


edited_rows = \

[loadAmrCsRow(row, this_day) \

for row in in_cur if row[i.meter_num].isdigit() and \
0 <= row[i.endpointid] and 0 <= row[i.meter_num] ]

for out_row in edited_rows:

print(out_row)

.

.

.

As I am learning more about the language, it appears it is more language efficient to use list comprehensions, and they seem to work quite well with database queries.

Advertisements

Leave a comment

Filed under General

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s