Lambda,List Comprehension,Map and Filter

tupples的妙用

def smallest(alist):
  smallest = 1000000
  smallestPos = -1
  for pos, value in enumerate(alist):
    if value < smallest:
      smallest = value
      smallestPos = pos
  return smallest, smallestPos
  • 在这个函数中,pos,value是一个tupple(pos,value),返回值smallest,smallestPos也是一个tupple(smallest,smallestPos)。所以用tupple可以返回多个函数值。
  • enumerate([1,2,3]) = [(0,1),(1,2),(2,3)]
  • 用代码x,y = y,x可以互换x,y的值,这点和其他语言不同。

python中function的特性

  • 在python中,function可以像变量一样,可以赋值给其他变量,作为参数和返回值。
  • First class citizen

Types one can assign to a variable, one can pass as arguments to functions and that can be return types of functions are called First class citizen of a language.

lambda

lambda expression是你不想想函数名字,而且函数比较简单时可以使用。lambda函数也是函数,所以它也是First class citizen。

f = lambda x: 2*x
def test(f,x,y):
  return f(x,y)
print(test(lambda x,y:x+y,1,2))
def ff():
  return lambda x: x*2
 print(ff()(1))

这里的ff()(1)是把1作为参数,传到ff函数里。

print((lambda x,y: x+y)(11,12))

这里也是同理,把11,12作为参数传到lambda函数里。

List Comprehension

List comprehensions provide a nice syntax for transforming a list into some new list.

  • 表达式
    [oprate for x in list]
  • 几种类型
print([abs(x) for x in [1,-1,3,-5]])
print([x for x in [1,-1,3,-5] if x>0])
print([-1 if x==0 else x for x in [1,0,3,0]])
print([(x,y) for x in ["apple","pie"] for y in [6,7,8,9,10]])

Map

Map is a function that applies a function to each element of the list and stores the results in a new list.

  • 表达式
    map(function, list)
print(map(x>2), [0,1,2,3])

注意:这条语句的运行结果是

[False, False, False,True]

Filter

Filter is a function that applies a function to choose special element of the list and stores the results in a new list.

def filt2(function,alist):
    result = []
    for x in alist:
        if function(x):
            result.append(x)
    return result

print(filt2(lambda x:x>0,[-1,2,-3,5,-5,7]))

flit2是一个Filter函数,lambda x:x>0是条件函数,[-1,2,-3,5,-5,7]是被过滤的list。

你可能感兴趣的:(Lambda,List Comprehension,Map and Filter)