Do you have a question? Post it now! No Registration Necessary. Now with pictures!
February 11, 2005, 9:02 pm
rate this thread
# David Eppstein of the Geometry Junkyard fame gave this elegant
# version for returing all possible pairs from a range of n numbers.
return dict([('%d,%d'%(i+1,j+1),(i+1,j+1)) for j in range(n) for i
# this construct uses a irregular syntax to generate a expression
# built by nested loops. Semantically, this expression generation is
# akin to applying a function to a tree. Morons in the computing
# industry and academia like to call this "list comprehension".
# In Python, this syntax irregularity works like this, for example:
# double each number from 1 to 5
myExpression = [ i*2 for i in range(1,6)]
# built a list of couples of the form (n*2,n*3)
myExpression = [ (i*2,i*3) for i in range(1,6)]
# in general the this expression generating syntax has the form
# [<expression> <iteration>]
# the iteration part can be nested.
myExpression = [ (i,j) for i in range(1,6) for j in range(1,4)]
# remember, this jargonized "list comprehension" is nothing more
# a irregular syntax for building a expression from nested loops. Its
# purpose is primarily of syntactical convenience. Advanced languages
# such as functional languages often have this power without the
# syntax irregularity.
# For Python's official tutorial on this topic, see
# Perl does not contain facilities to generate expressions based on
# trees. Of course, one can just do with for loops. One can however
# write a function that are syntactically more succinct in generating
# expression thru trees than the so-called "list comprehension"),
# look for the function named Table.
his is Perl-Python a-day. To subscribe, see