# newbie: working iwth list of tuples

Raymond Hettinger python at rcn.com
Sun Jan 29 09:04:55 CET 2006

```[Raymond Hettinger]
> Parameterized filter, extract, and reduce functions can be handled in a
> like manner.

Just for grins, here is a more worked-out example:

def pfunc(inputfields, operation):
"Parameterized computation of a new field"
# For example, append a field that is the sum of fields 1 and 3:
#    z = pfunc((1, 3), operator.add)
#    print map(z, database)
def z(record):
newfield = operation(*[record[f] for f in inputfields])
return record + (newfield,)
return z

def rfunc(inputfield, operation):
"Parameterized reduce operation"
#
# For example, find the maximum value of field 2:
#    r = rfunc(2, max)
#    print reduce(r, database)
def z(cumval, record):
x = record[inputfield]
return operation(cumval, x)
return z

def filt_func(inputfields, operation):
"Parameterized filter operation"
#
# For example, get records where field1 < field2:
#    f = filt_func((1, 3), operator.lt)
#    print filter(f, database)
def z(record):
i, j = inputfields
return operation(i, j)
return z

def xfunc(fields):
"Parameterized extract operation"
#
# For example, extract fields 1, 3, and 4
# x = xfunc((1,3,4))
# print map(x, database)
def z(record):
return tuple([record[f] for f in fields])
return z

# ---- The examples can be run on the following sample database: ----

database = [
(10, 25, 30, 40, 50, 60),
(100, 250, 300, 400, 500, 600),
(1, 2.5, 3, 4, 5, 6),
]

```

More information about the Python-list mailing list