2005-01-17
To remove elements in a list that satisfies some criterion, use the function “filter(testFunction,list)”. The “testFunction” will be applied to each element in the list. If testFunction(element) returns False, then that element will not be in the resulting list.
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))
Reference: Python Doc↗.
Use “grep” to remove elements in a list. The form is “grep {testFunction $_} myList”. Example:
use Data::Dumper; sub even {return $_[0]%2==0}; print Dumper[ grep {even $_} (0..10)];
In perl in general, “$_” means the entire argument(s) given to a subroutine. “$_[0]” means the first argument. The “(0..10) generate a list from 0 to 10”.
Use “map” to apply a function to a list. The basic form is “map {myFunction($_)} myList”.
use Data::Dumper; sub square {return ($_[0])**2;}; print Dumper [ map {square($_)} (0..10)];
The “Data::Dumper” module is to import the “Dumper” function for printing lists. The “%” is the operator for computing remainder. The “**” is the exponential operator.
Reference: perldoc Data::Dumper↗.
Reference: perldoc -f grep↗.
Reference: perldoc -f map↗.
See also:
Page created: 2005-01. © 2005 by Xah Lee.