python list comprehension compared with the filter and map

First introduced to the filter and map:

filter:

filter ()  function is used to filter sequences, filtered ineligible element returns a list of qualified new elements.

The receiving two parameters, as a function of a first, a second sequence, each element of the sequence as an argument to a function arbitrates, then return True or False, and finally returns True new elements into the list.

filter ( function , Iterable ): function: a function of determining, iterable: iterables

def is_odd(n):
    return n % 2 == 1
 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)

# [1, 3, 5, 7, 9]

map:

the Map ( function , Iterable , ...) will do the mapping function in accordance with the specified sequence provided. The first parameter argument function to call the function function of each element in the sequence, each time the function returns a new list of function return values.

Python 2.x return list.

Python 3.x returns an iterator.

DEF Square (X):             # calculates the square of 
     return X ** 2 

Map (Square, [ 1,2,3,4,5])    # calculates the square of each element of a list 
# [1, 4, 9, 16, 25] 
Map ( lambda X: X ** 2, [1, 2,. 3, 4,. 5])   # using lambda anonymous function 
# [1, 4, 9, 16, 25] 
 
# two lists, the same position adding data list 
Map ( the lambda X, Y: X + Y, [. 1,. 3,. 5,. 7,. 9], [2,. 4,. 6,. 8, 10 ])
 # [. 3,. 7,. 11, 15, 19]

 

List comprehension compared with the filter and map

symbols = '$¢£¥€¤'
beyond_ascii = [ord(s) for s in symbols if ord(s) > 127]
print(beyond_ascii)
# [162, 163, 165, 8364, 164]
beyond_ascii = list(filter(lambda c: c > 127, map(ord, symbols)))
print(beyond_ascii)
# [162, 163, 165, 8364, 164]

 

Guess you like

Origin www.cnblogs.com/xiangxiaolin/p/11571492.html