python基础12_匿名_内置函数

一个二分查找的示例:

# 二分查找 示例
data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35, 36, 66]


def binary_search(dataset, find_num):
    print(dataset)

    if len(dataset) > 1:
        mid = int(len(dataset) / 2)
        if dataset[mid] == find_num:  # find it
            print("找到数字", dataset[mid])
        elif dataset[mid] > find_num:  # 找的数在mid左面
            print("\033[31;1m找的数在mid[%s]左面\033[0m" % dataset[mid])
            return binary_search(dataset[0:mid], find_num)
        else:  # 找的数在mid右面
            print("\033[32;1m找的数在mid[%s]右面\033[0m" % dataset[mid])
            return binary_search(dataset[mid + 1:], find_num)
    else:
        if dataset[0] == find_num:  # find it
            print("找到数字啦", dataset[0])
        else:
            print("没的分了,要找的数字[%s]不在列表里" % find_num)


binary_search(data, 66)

关于匿名函数 lambda

#!/usr/bin/env python
# coding:utf-8

# 这段代码
# def calc(n):
#     return n ** n
#
#
# print(calc(10))

# 换成匿名函数
calc = lambda n: n ** n
print(calc(3))

######
# 匿名函数通常用简单逻辑,与其它函数配合使用
lambda x, y, z: (x + 1, y + 1, z + 1)


### 编程的方法论:
# 面向过程
# 函数式
# 面向对象
def foo(name):
    print(name)


def bar(name):
    print("my name is %s" % name)

print(foo(bar('aa')))
print('----------------')


lis = [333,222,111,11,22,33,44,55,66,888]
print(max(lis))

dic = {'k1': 10, 'k2': 100, 'k3': 30}

# print("用max来求dic的最大值:",max(dic.values()))
print("用max来求dic的最大key值:", max(dic))
print(dic[max(dic, key=lambda k: dic[k])])
print('===========')
### 使用map 和匿名函数 求平方
res = map(lambda x: x ** 2, [1, 5, 7, 4, 8])

for i in res:
    print(i)

print(res, type(res))

##
listx = [1, 2, 3, 4, 5, 6, 7]  # 7 个元素
listy = [2, 3, 4, 5, 6, 7]  # 6 个元素
listz = [100, 100, 100, 100]  # 4 个元素
list_result = map(lambda x, y, z: x ** 2 + y + z, listx, listy, listz)
print(list(list_result))

# 由于 lambda 中的 z 参数,实际是使用了 listz, 而 listz 里面只有 4 个元素,
#  所以,只执行了 4 个元素的的计算。

学了好几节的东西,放在一起了。

## 高阶函数: 1.函数接收的参数是一个函数名; 2.返回值中包含函数
# 把函数当作参数传递给另外一个函数
# def foo(n):
#     print(n)
#
# def bar(name):
#     print("My name is %s" % name)
#
# foo(bar)
# foo(bar('alex'))

def bar():
    print("from bar")

def foo():
    print("from foo")
    return bar

foo()()


def handle():
    print("from handle...")
    return handle

h = handle()
h()


def test1():
    print("from test1")

def test2():
    print('from test2')
    return test1()

test2()


### 尾调用: 在函数的最后一步调用另外一个函数(不一定是最后一行。)
## 优化:把递归放在最后一步。

map  / reduce  / filter  跟大数据沾点边 

#### map函数,第一个参数是方法,第二个参数是迭代器(可迭代对象)
## python2中,map的结果直接是列表

msg = 'abcdefg'
print(list(map(lambda x: x.upper(), msg)))  # 简洁,但可读性很差。


lis = (11, 22, 33, 44, 55, 66,)

def abc(x):
    return x // 2 + 1

res = map(abc,lis) #也可以传一个自定义的函数
for i in res:
    print(i)
#!/usr/bin/env python
# coding:utf-8

## python2中可直接用。但是3中需要导入模块。
from functools import  reduce

lis = [3,4,5,7,32,22,11]
print(reduce(lambda x,y:x+y,lis))

# 用来合并一个序列
# 带有初始值的 reduce
print(reduce(lambda x,y:x+y, lis, 100))
#!/usr/bin/env python
# coding:utf-8

### filter函数 用来过滤迭代器,得到过滤出的对象

lis = ['alex_sb', 'abc_tom', 'dadasb', 'jerry', 'hhui_sb']

# 不保留 sb 结尾的元素
res = list(filter(lambda x: not x.endswith('sb'), lis))
print(res)


## 保留以 a 开头的元素
print(list(filter(lambda y:y.startswith('a'),lis)))


# filter 练习: 过滤出小于33岁的。
dic = [
    {'name':'alex', 'age':99},
    {'name':'wpq', 'age':66},
    {'name':'bigs', 'age':44},
    {'name':'tom', 'age':22},
    {'name':'jerry', 'age':33},
]

print(list(filter(lambda n: n['age']<=33, dic)))

python中常用的一些内置函数,更详细的内置函数,可参考:http://www.runoob.com/python/python-built-in-functions.html

#!/usr/bin/env python
# coding:utf-8

print(abs(-3)) # 求绝对值

# 所有元素是否不为 0、''、False ,三样都没有,则返回True
# 空列表、元组、字典都为True
print(all(''))
print(all([]))
print(all(()))
print(all({}))
print(all(['2','1',''])) # 返回false
print(all([2,1,0])) # 返回false

# 与all不同,如果有一个非0,非空,非false,则返回True
print(any(['2',''])) # 任何一个为真即返回True


print(bin(9)) # 转为二进制
print(hex(9)) # 转为16进制
print(oct(9)) # 转为8进制


print(bool(''))


name='你好'
## 转码为字节
print(bytes(name,encoding='utf-8'))
print(bytes(name,encoding='utf-8').decode('utf-8'))

print(bytes(name,encoding='gbk'))
print(bytes(name,encoding='gbk').decode('gbk'))


print(chr(46)) # 转为ascii码


print(divmod(10,3)) # 10除3, 取出商和余


str_dic="{'name':'alex'}"
print(str_dic)
dic = eval(str_dic)  # 识别字符串中的字典
print(dic['name'])


str2= '1+3+5*2'
print(str2)
print(eval(str2))  # 识别字符串中的表达式,并得出结果


## 可hash的数据类型即不可变数据类型。 不可hash的即可变类型
## 应用: 检验软件下载的hash
## 不能通过hash值反推原始值 。

name ='alex'
print(hash(name))
print(hash(name))
name = 'sb'
print(hash(name))


print(dir(hash))
print(help(hash))


print(globals()) ## 输出全局变量
print(__file__)  ##当前文件路径

def test():
    age=19
    print(globals())
    print('----------------------')
    print(locals()) ##输出当前作用域的变量

test()

猜你喜欢

转载自www.cnblogs.com/frx9527/p/python_12.html