python的高级操作
1.字典排序
字典通过值由小到大排序:
d = {"a": 5, "c": 2, "h": 8, "k": 4}
sort_d = sorted(d.items(), key=lambda x: x[1])
print(sort_d)
# 结果 [('c', 2), ('k', 4), ('a', 5), ('h', 8)]
2. 列表生成式
[x*11 for x in range(10)]
3.给定两个 list A ,B,请用找出 A ,B 中相同的元素,A ,B 中不同的元素
A、B 中相同元素:print(set(A)&set(B))
A、B 中不同元素:print(set(A)^set(B))
3. cProfile来分析代码的运行时间
import random
import cProfile
lIn = [random.random() for i in range(100000)]
def f1(lIn):
l1 = sorted(lIn)
l2 = [i for i in l1 if i<0.5]
return [i*i for i in l2]
def f2(lIn):
l1 = [i for i in lIn if i<0.5]
l2 = sorted(l1)
return [i*i for i in l2]
def f3(lIn):
l1 = [i*i for i in lIn]
l2 = sorted(l1)
return [i for i in l1 if i<(0.5*0.5)]
cProfile.run('f1(lIn)')
cProfile.run('f2(lIn)')
cProfile.run('f3(lIn)')
# ncalls
# 该函数的调用次数
# tottime
# 总执行时间
# percall
# 函数每个调用的总时间
# cumtime
# 函数的累计时间
# percall
# 每个调用的累计时间
# filename:lineno(function)
# 名称、行号和涉及到的函数
4. map函数使用
# function_to_apply:代表函数
# list_of_inputs:代表输入序列
map(function_to_apply, list_of_inputs)
# map使用匿名函数:
input_list = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**6, input_list))
# map也可以自定义函数
input_list = [1, 2, 3, 4, 5]
def func(x):
return x**6
squared = list(map(func, input_list))
5.reduce函数使用
# function:代表函数
# iterable:序列
# initializer:初始值(可选)
reduce(function, iterable[, initializer])
reduce实现10的阶乘
# 导入reduce
from functools import reduce
# 定义函数
def f(x,y):
return x*y
# 定义序列,含1~10的元素
items = range(1,11)
# 使用reduce方法
result = reduce(f,items)
print(result)
# 匿名函数实现
n = 10
reduce(lambda x,y: x*y, range(1,n+1))
6.filter函数
用于过滤序列,过滤掉不符合条件的元素,返回由符合条件的元素组成的新列表
# function 判断函数
# iterable 可迭代对象
filter(function,iterable)
list_input = [4,9,3,14,7,10,6,1]
def is_odd(x):
return x % 2 == 1
newlist = list(filter(is_odd,list_input))
print(newlist)
# 输入结果
# [9, 3, 7, 1]