内置函数:
可以用lamba函数对字典进行排序。(字典没有内置函数,不能用dict.sort()排序)
dic = {'b':5, 'a':3, 'c':4}
# 直接用python函数sorted:
print(sorted(dic))
# output:['a', 'b', 'c']
print(sorted(dic.items())) # 对key排序:
# output:[('a', 3), ('b', 5), ('c', 4)]
print(sorted(dic.items(), key = lambda x:x[1], reverse=True)) # 用lambda函数指定排序元素
# output:[('b', 5), ('c', 4), ('a', 3)]
print(sorted(dic.values())) # 只对值排序
# output:[3, 4, 5]
print(sorted(dic.values(), reverse = True)) # 只对值逆序
# output:[5, 4, 3]
列表元素为字典时,可以指定字典元素进行排序。
list1 = [
{'name':'joe', 'age':'18'},
{'name':'susan', 'age':'19'},
{'name':'tom', 'age':'17'}
]
print(sorted(list1, key = lambda x:x['name']))
# output:[{'name': 'joe', 'age': '18'}, {'name': 'susan', 'age': '19'}, {'name': 'tom', 'age': '17'}]
print(sorted(list1, key = lambda x:x['age']))
# output:[{'name': 'tom', 'age': '17'}, {'name': 'joe', 'age': '18'}, {'name': 'susan', 'age': '19'}]
常用内置函数:
方法 | 描述 | 例子 |
abs() | 函数返回数字的绝对值 | num = -1 print(abs(num)) # output:1 |
sorted(list) | 排序,返回排序后的list | print(sorted(['a','b','','d'])) # output:['', 'a', 'b', 'd'] |
sum(list) | 求list元素的和 | sum([1,2,3]) # output:6 |
round(a, b) | 获取指定位数的小树。a是浮点数,b是要保留的位数 | round(3.1415926) # output:3.14 |
isinstance(a, b) | 类型判断,a是要判断的变量,b是类型 | num = 1 print(isinstance(num,int)) # output:True |
eval() | 执行一个表达式,或字符串作为运算 | eval('1+1') # output:2 |
exec() | 输出python语句 | exec('print("Python")') # output:Python |
内置函数可以通过dir(__builtins__)查询。
高阶函数:
方法 | 描述 |
map(func, seq[,seq[,seq...]]) - > list |
接收一个函数及多个集合序列,会根据提供的函数对指定序列做映射,然后返回一个新的map对象。 |
filter(func, seq) - > list or tuple or string |
用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的filter对象。 |
reduce(func, seq[, initvalue]) | 对于序列中的所有元素调用func进行数据合并操作,可以给定一个初始值。 |
map:
例1:
list1 = [1,2,3,4,5]
# map
new_list = map(lambda x:x*2, list1)
print(new_list)
# output:<map object at 0x0000013AB0630128>
print(list(new_list)) # 将map对象转换为list
# output:[2, 4, 6, 8, 10]
# 或者
print([x*2 for x in list1])
# output:[2, 4, 6, 8, 10]
例2:
list1 = [1,3,5,7,9]
list2 = [2,4,6,8,10]
# map
new_list = map(lambda x, y : x*y, list1, list2)
print(new_list)
# output:<map object at 0x0000013AB0630128>
print(list(new_list)) # 将map对象转换为list
# output:[2, 12, 30, 56, 90]
# 即对应元素相乘
# 或者
print([x*y for x,y in zip(list1, list2)])
# output:[2, 12, 30, 56, 90]
filter:
例1:
list1 = [1,3,5,7,9]
# filter
new_list = filter(lambda x : x>4, list1)
print(new_list)
# output:<filter object at 0x0000013AB0692470>
print(list(new_list)) # 将map对象转换为list
# output:[5, 7, 9]
# 或者
print([x for x in list1 if x > 4])
# output:[5, 7, 9]
把上面的filter改成map:
new_list = map(lambda x : x>4, list1)
print(list(new_list)) # 将map对象转换为list
# output:[False, False, True, True, True]
所有,map表示映射,filter表示筛选,二者不可互换。
reduce:
例:
from functools import reduce
list2 = [2,4,6,8,10]
reduce(lambda x,y:x+y, list2)
# output:30
# x+y: 2+4, 返回6
# x+y: 6+6, 返回12
# x+y: 12+8,返回20
# x+y: 20+20,返回30
reduce(lambda x,y:x+y, list2, 5)
# output:35
# x+y: 5+2, 返回7
# x+y: 7+4, 返回11
# ……