一个专注于计算机编程和硬件学习的博客主
9/2
2019

Python--高阶内置函数、处理错误异常

以自定义PE_ratio为例写文档

def PE(Price,Earning):
    """Calculate PE ratio"""
    PE=Price/Earning
    return print(PE)
--------------------
PE.__doc__
'Calculate PE ratio'

lambda表达式

  • 创建一个匿名函数
  • 在函数中包函数用到的比较多
  • 更加简洁
super_add = lambda num1, num2: num1+num2

print(super_add(120,230))
-------------------------
350

高阶内置函数filter()批量删选虚假姓名

  • filter(n,m)

    • n为筛选条件
    • m为需要筛选的元素
names = ['Tom', 'William',
         'Mokey DDDDDDDDDD Lufy',
         'Mary', 'Jary']
def fake_name(name):
    return len(name) > 20
fake_names = list(filter(fake_name, names))
print(fake_names)
-------------------------
['Mokey DDDDDDDDDD Lufy']
  • filter(fake_name,names)

    • fake_name为算选条件,使用自定义函数进行筛选
    • names为需要进行赛选的元素,一个一个进去筛选

高阶内置函数map()

def square(x):
    return x**2
list_1 = [1,2,3,4,5,6,7,8,9]
a = list(map(square,list_1))
print(a)
---------------------------------
[1, 4, 9, 16, 25, 36, 49, 64, 81]
  • map(square,list_1)list_1元素依次进入到square函数中进行运算

地区平均信用质量

score_cards = [[1,2,3,4,5,3,4,1,2,4],
               [6,5,7,6,5,7,5,8,9,7],
               [9,10,9,8,9,10,10,9,10,9]]
def mean(score_list):
    return sum(score_list)/len(score_list)

averge_scord = map(mean,score_cards)
print(list(averge_scord))
-------------------------
[2.9, 6.5, 9.3]

利用lambda简化

score_cards = [[1,2,3,4,5,3,4,1,2,4],
               [6,5,7,6,5,7,5,8,9,7],
               [9,10,9,8,9,10,10,9,10,9]]
average_scores = map(lambda x:sum(x)/len(x),
                     score_cards)
print(list(average_scores))
---------------------------
[2.9, 6.5, 9.3]

处理错误和异常

try except finally
while True:
    try:
        x=int(input('Enter a int number please: '))
        break
    except:
        print('That is notcorrect,Are you kiding???')
    finally:
        print('You have enter a number.')
-----------------------------------------
Enter a number please: 10
You have enter a number.
  • try—试着去运行里面的程序,如果出错则停止try里面的程序而去执行 except里面的程序,后再执行finally里面的程序,如果正确,则跳过except里面的程序,直接去执行finally里面的程序.

添加新评论