[Tutor] python equivalents for perl list operators?
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Apr 23 03:48:36 EDT 2016
On 23/04/16 01:15, Malcolm Herbert wrote:
> @raw = (2, 1, 4, 3);
> @grepped = grep { $_ >= 3 } @raw; # (4, 3)
grepped = [item for item in raw if item >= 3]
> @mapped = map { $_ + 1 } @raw; # (3, 2, 5, 4)
mapped = [item +1 for item in raw]
or
mapped = map(lambda x: x+1, raw)
> @sorted = sort { $a > $b } @raw; # (1, 2, 3, 4)
raw.sort() # sorts in place
_sorted = sorted(raw)
You can add parameters to both functions to specify
sort characteristics, for example:
raw2 = [(1,'p'),(2,'e'),(3,'r'),(4,'l')]
lexical = sorted(raw2,key=lambda t:t[1])
You can use the interpreter to find out some of this
by using the help() function
help([]) # help on all list methods
help([].sort) # help on the sort method
There are also some modules that might be of interest
to you such as itertools and functools.
You might also find the Functional Programming
topic in my tutorial useful (see below).
hth
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list