流畅的python_【流畅的python】学习笔记

fa412981aa446f7c3a1fe1792f9efa51.png

map filter函数

def is_even(n):
    return n%2 == 0

print(list(map(is_even, range(10))))
print([is_even(i) for i in range(10)])
print(list(map(is_even, filter(lambda n: n>5, range(10)))))
print([is_even(i) for i in range(10) if i > 5])


输出
[True, False, True, False, True, False, True, False, True, False]
[True, False, True, False, True, False, True, False, True, False]
[True, False, True, False]
[True, False, True, False]

reduce函数

from functools import reduce
print(reduce(lambda x,y: x+y, range(100)))
print(sum(range(100)))


输出
4950
4960

all和any

flag_1 = [1,1,1,1,1,1]
flag_2 = [1,0,1,0,0,1]
print(all(flag_1), all(flag_2))
print(any(flag_1), any(flag_2))


输出
True False
True True

匿名函数

fruits = ['apple', 'banana', 'strawberry', 'cherry']
print(sorted(fruits, key= lambda word: word[::-1]))


输出
['banana', 'apple', 'strawberry', 'cherry']

把函数作为参数传递

def factorial(n):
    '''returns n!'''
    return 1 if n<2 else n*factorial(n-1)

print(factorial(42))
print(factorial.__doc__)
print(type(factorial))

fact = factorial
print(fact)
print(fact(5))
for i in map(factorial, range(11)):
    print(i)
for i in map(lambda x: x**2, [1,2,3,4,5]):
    print(i)
print(list(map(factorial, range(11))))

#高阶函数
fruits = ['apple', 'banana', 'strawberry', 'cherry']
print(sorted(fruits, key=len))

def reverse(word):
    return word[::-1]
word = 'apple'
print(reverse(word))
print(sorted(fruits, reverse))


输出
1405006117752879898543142606244511569936384000000000
returns n!
<class 'function'>
<function factorial at 0x1099b9440>
120
1
1
2
6
24
120
720
5040
40320
362880
3628800
1
4
9
16
25
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
['apple', 'banana', 'cherry', 'strawberry']
elppa
['banana', 'apple', 'strawberry', 'cherry']

可调用对象

import random
class BingoCage:
    def __init__(self,items):
        self._items = items
        random.shuffle(self._items)
    def pick(self):
        try:
            return self._items.pop()
        except IndexError:
            raise LookupError('pick from empty BingoCage')
    def __call__(self):
        return self.pick()

bingo = BingoCage([0,1,2])
print(bingo.pick())
print(bingo())
print(bingo())
print(callable(bingo))


输出
1
0
2
True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值