三元表达式、递归、匿名与内置函数

一、三元表达式

应用于:

1、条件成立返回 一个值
2、条件不成立返回 一个值

示例:

x=12
y=11
res=x if x > y else y
print(res)

''' 12 '''


def max2(x,y):
    return x if x > y else y

print(max2(10,11))

''' 11 '''

二、函数递归

#函数递归:函数的递归调用,即在函数调用的过程中,又直接或间接地调用了函数本身
# 直接调用
def foo():
    print('from foo')
    foo()
foo()

# 间接调用
def bar():
    print('from bar')
    foo()

def foo():
    print('from foo')
    bar()
foo()

# 递归分为两个阶段
#1、回溯:
    # 注意:一定要在满足某种条件结束回溯,否则的无限递归
#2、递推

# 总结:
#1、递归一定要有一个明确地结束条件
#2、没进入下一次递归,问题的规模都应该减少
#3、在python中没有尾递归优化

示例:

items=[1,[2,[3,[4,[5,[6,[7,[8,[9,[10,]]]]]]]]]]
def tell(l):
    for item in l:
        if type(item) is not list:
            print(item,end='')
        else:
            tell(item)

tell(items)

''' 12345678910 '''

三、匿名函数

1 匿名的目的就是要没有名字,给匿名函数赋给一个名字是没有意义的
2 匿名函数的参数规则、作用域关系与有名函数是一样的
3 匿名函数的函数体通常应该是 一个表达式,该表达式必须要有一个返回值
f=lambda x,n:x ** n
print(f)
print(f(2,3))

'''
<function <lambda> at 0x02C00858>
8
'''

四、内置函数

print(all([1,'a',True])) # 列表中所有元素的布尔值为真,最终结果才为真
print(all('')) # 传给all的可迭代对象如果为空,最终结果为真

print(any([0,'',None,False])) #列表中所有元素的布尔值只要有一个为真,最终结果就为真
print(any([])) # 传给any的可迭代对象如果为空,最终结果为假
'''
True
True
False
False
'''


print(bin(11)) #十进制转二进制
print(oct(11)) #十进制转八进制
print(hex(11)) #十进制转十六进制

'''
0b1011
0o13
0xb
'''
print(bool(0)) #0,None,空的布尔值为假
''' False '''

res='你好egon'.encode('utf-8') # unicode按照utf-8进行编码,得到的结果为bytes类型
# res=bytes('你好egon',encoding='utf-8') # 同上
print(res)
''' b'\xe4\xbd\xa0\xe5\xa5\xbdegon' '''
# def func():
#     pass

print(callable('aaaa'.strip)) #判断某个对象是否是可以调用的,可调用指的是可以加括号执行某个功能
''' True '''

# print(chr(90)) #按照ascii码表将十进制数字转成字符
# print(ord('Z')) #按照ascii码表将字符转成十进制数字


print(dir('abc')) # 查看某个对象下可以用通过点调用到哪些方法

# print(divmod(1311,25)) # 1311 25
''' ……, '__iter__', '__le__', '__len__', ……'''

# 将字符内的表达式拿出运行一下,并拿到该表达式的执行结果
res=eval('2*2')
print(res,type(res))

res1=eval('[1,2,3,4]')
print(res1,type(res1))

res2=eval('{"name":"egon","age":18}')
print(res2,type(res2))

'''
4 <class 'int'>
[1, 2, 3, 4] <class 'list'>
{'name': 'egon', 'age': 18} <class 'dict'>
'''

# db.txt:  {"egon":"123","alex":"456"}
with open('db.txt','r',encoding='utf-8') as f:
    s=f.read()
    dic=eval(s)
    print(dic,type(dic))
    print(dic['egon'])
'''
{'egon': '123', 'alex': '456'} <class 'dict'>
123
'''

s={1,2,3}
s.add(4)
print(s)
''' {1, 2, 3, 4} '''

 剩余

l=[1,4,3,5]
res=reversed(l)
print(res)
print(list(res))
'''
<list_reverseiterator object at 0x014A0FB0>
[5, 3, 4, 1]
'''


# print(round(3.5))   #4
# print(round(3.4))   #3

sc=slice(1,5,2) #1:5:2
l=['a','b','c','d','e','f']
print(l[1:5:2])
print(l[sc])
'''
['b', 'd']
['b', 'd']
'''

# sum
# print(sum([1,2,3,4]))


# zip
left='hello'
right={'x':1,'y':2,'z':3}

res=zip(left,right)
print(list(res))

''' [('h', 'x'), ('e', 'y'), ('l', 'z')] '''

 

posted @ 2020-07-16 09:06  zh_小猿  阅读(143)  评论(0编辑  收藏  举报