python3中的一些实用技巧 (持续更新)

1、递归求和

i=1
sum=0
def he(i,sum):
    sum+=i
    if i<10:
        i+=1
        return he(i,sum)
    print(sum)
he(i,sum)

2、集合去重

list=['a','d','s','f','a','a','f']
set=set(list)
print(set) 

3、装饰器记录程序运行时间

def count_time(func):
   def int_time(*args, **kwargs):
       start_time = datetime.datetime.now()  # 程序开始时间
       func()
       over_time = datetime.datetime.now()   # 程序结束时间
       total_time = (over_time-start_time).total_seconds()
       print('程序共计%s秒' % total_time)
   return int_time


@count_time
def main():
   print('>>>>开始计算函数运行时间')
   for i in range(1, 1000):# 可以是任意函数  , 这里故意模拟函数的运行时间
       for j in range(i):
           print(j)

4、map函数配合匿名函数

x=[1,2,3]
y=map(lambda x:x+1,x) 
print(list(y))
print("hello" if True else "world")

5、zip的使用

list=[1,2,3,4,4,4,5,5,5,5]
print(max(set(list),key=list.count))
使用两个相关的序列构建一个字典
t1=(1,2,3)
t2=(10,20,30)
print(dict(zip(t1,t2)))

6、

斐波那契函数
def fibonacci(n):    
    a, b, counter = 0, 1, 0
    while True:
        if counter > n:
            return
        yield a             # yield让该函数变成一个生成器
        a, b = b, a + b
        counter += 1

fib = fibonacci(10)           # fib是一个生成器
print(type(fib))
for i in fib:
    print(i, end=" ")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值