[Tutor] python equivalents for perl list operators?
Malcolm Herbert
python.org at mjch.net
Fri Apr 22 20:15:52 EDT 2016
hey folks - I've been a long time perl programmer and only recently
tried my hand a python, so it's probable that these questions are
non-sensical in this context but for the moment I'm trying to stay
afloat
I've been dabbling a bit with some lists and trying to work out how best
to abitrarily sort and filter these. Perl has a number of operators that
help with this in map(), grep() and sort() as follows:
@raw = (2, 1, 4, 3);
@grepped = grep { $_ >= 3 } @raw; # (4, 3)
@mapped = map { $_ + 1 } @raw; # (3, 2, 5, 4)
@sorted = sort { $a > $b } @raw; # (1, 2, 3, 4)
in this case:
grep() will return all list items for which the code block returns true
map() will return all list items as modified by the code block
sort() will return a sorted list of items, using the code block to
compare them (where $a and $b represent two items to be compared)
so - I've been able to at least work out the map() case above with a
list comprehension
raw = [2, 1, 4, 3]
mapped = [ x + 1 for x in raw] # [3, 2, 5, 4]
and I know that .sorted() would do what I want in this limited example,
but I'm after the ability to put abitrary code in here to determine
sort order or test an item for filtering (because the items they're
testing may be complex structures rather than these simple integers, for
example)
these seem so useful things to want to do that I'd imagine they're
probably a basic part of the language, but so far I've not seen anything
that might cover them with the exeption of map() as above - I am slowly
trawling my way through Learning Python (5ed) so I might yet get to
something related, I don't know
does anyone have any pointers? ta
Regards,
Malcolm
--
Malcolm Herbert
mjch at mjch.net
More information about the Tutor
mailing list