# fun : a function applying to the iterable object # iterable : such as list, tuple, string and other iterable object map(fun, *iterable) # * token means that multi iterables is supported
map()
applying the given function to each item of the given iterable object.python
map()
returns an iterable object called "map object".app
# eg 1 def addition(n): return n + n numbers = (1, 2, 3, 4) result = map(addition, numbers) print(list(result)) >>>[2,4,6,8] # eg 2 numbers = (1, 2, 3, 4) result = map(lambda x: x + x, numbers) print(list(result)) >>>[2,4,6,8] # eg 3 - multi iterables numbers1 = [1, 2, 3] numbers2 = [4, 5, 6] result = map(lambda x, y: x + y, numbers1, numbers2) print(list(result)) >>>[5,7,9]
# fun : a function that tests if each element of the sequence true or not. # sequence : who needs to be filtered, it can be sets, lists, tuples, or containers of any iterators. filter(fun, sequence)
filter()
applying the given function to each item of the given sequence object, and remain the eligible element.code
filter()
returns an iterator that is already filtered.token
# eg 1 seq = [0, 1, 2, 3, 5, 8, 13] result = filter(lambda x: x % 2 == 0, seq) print(list(result)) >>>[0, 2, 8]
# fun : a function applying to all elements of the sequence. # sequence : who needs to be computered by itself, it can be sets, lists, tuples, or containers of any iterators. filter(fun, sequence)
from functools import reduce lis = [1, 3, 5, 6, 2] print (reduce(lambda a,b : a+b,lis)) print (reduce(lambda a,b : a if a > b else b,lis)) >>>17 >>>6
zip(*iterators) # * token means that multi iterators is supported
zip()
returns a single iterator object, having mapped values from all the containers.ip
# 1. How to zip the iterators? name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ] roll_no = [ 4, 1, 3, 2 ] marks = [ 40, 50, 60, 70 ] mapped = list(zip(name, roll_no, marks)) print(mapped) >>>[('Shambhavi', 3, 60), ('Astha', 2, 70),('Manjeet', 4, 40),('Nikhil', 1, 50)] # 2. How to unzip? namz, roll_noz, marksz = zip(*mapped) # 3. How to traversal them? players = [ "Sachin", "Sehwag", "Gambhir", "Dravid", "Raina" ] scores = [100, 15, 17, 28, 43 ] for pl, sc in zip(players, scores): print ("Player : %s Score : %d" %(pl, sc)) >>> Player : Sachin Score : 100 Player : Sehwag Score : 15 Player : Gambhir Score : 17 Player : Dravid Score : 28 Player : Raina Score : 43