[perl-python] 20050117, filter, map

Xah Lee xah at xahlee.org
Mon Jan 17 03:48:59 CET 2005


© # -*- coding: utf-8 -*-
© # Python
©
© # the "filter" function can be used to
© # reduce a list such that unwanted
© # elements are removed.
© # example:
©
© def even(n): return n % 2 == 0
© print filter( even, range(11))
©
©
© # the "map" function applies a function
© # to all elements of a list. Example:
©
© def square(n): return n*n
© print map(square, range(11))
©
© ------------------------------------
© # similar perl versions
©
© use Data::Dumper;
© sub even {return $_[0]%2==0};
© print Dumper[ grep {even $_} (0..10)];
©
©
© # sub square {$n=shift;$n**2;};
© sub square {(shift)**2;};
© print Dumper [ map {square($_)} (0..10)];
©
© # the codes above showcase some syntax
© # variations commonly found in perl code
© # base
©
© -------------------------
©
© # in Mathematica for example, filter is
© # akin to Apply and map is MapThread.
© # The standard Map can be applied
© # according to a level spec of trees
© # and there's also MapAt, Nest,
© # NestList...any many more powerful
© # functions that manipulates trees.
© # lisp languages often have a subset
© # of it.
©
© ----------------------------
© Note: this post is from the Perl-Python
© a-day mailing list at
© http://groups.yahoo.com/group/perl-python/
© to subscribe, send an email to
© perl-python-subscribe at yahoogroups.com if
© you are reading it on a web page,
© program examples may not run because
© html conversion often breaks the code.
©
©   Xah
©   xah at xahlee.org
©   http://xahlee.org/PageTwo_dir/more.html




More information about the Python-list mailing list