Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > (patch for Bash) list comprehension and filtering

Reply
Thread Tools

(patch for Bash) list comprehension and filtering

 
 
William Park
Guest
Posts: n/a
 
      08-02-2004
1. Here is shell version of Python filter() for array. Essentially,
you apply a command on each array element, and extract only those
elements which it returns success (0). This is specialized form of
list comprehension where you can contruct an array from another
array, using some sort of test or filtering.

Usage is
arrayfilter [-a var] command array
where 'command' is a function, shell script, or external executable,
which takes one argument (ie. the array elements). If 'command'
return success (0), then print the element; and, if it fails
(non-zero), then skip the element. If -a option is given, then the
output will be save into array variable 'var', instead of default
stdout.

For example,
a=(1 a 2 b 3 c)
func () { [[ $1 == [a-z] ]]; }

arrayfilter func a --> a b c
arrayfilter -a b func a --> b[1]=a b[3]=b b[5]=c


2. More generally, here is shell version of Python list comprehension.
Idea is to apply some test or command on each array element, and
collect the outputs as parameter expansion. So, for each element of
array variable 'var',
${var| command }
will expand to the output of 'command' which takes one argument. If
'command' returns NULL, then that element is skipped. Usage is very
similar to other parameter expansion, and both '*' and '@' work as
expected.

For example,
a=(1 a 2 b 3 c)
func () { [[ $1 == [a-z] ]] && echo ".$1."; }

func x --> .x.
${a[*]| func } --> .a. .b. .d.


Ref:
http://freshmeat.net/projects/bashdiff/
http://home.eol.ca/~parkw/index.html#bash
help arrayfilter
help '${var|'

--
William Park, Open Geometry Consulting, <>
Toronto, Ontario, Canada
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
List comprehension in if clause of another list comprehension Vedran Furac( Python 4 12-19-2008 01:35 PM
Appending a list's elements to another list using a list comprehension Debajit Adhikary Python 17 10-18-2007 06:45 PM
List comprehension returning subclassed list type? Shane Geiger Python 4 03-25-2007 09:34 AM
Sorting and list comprehension Tran Tuan Anh Python 3 10-12-2004 07:17 AM
Mix lambda and list comprehension? Peter Barth Python 4 07-16-2003 11:20 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57