python的高级操作

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]
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曾晶的总结

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值