Python中高频代码


本文很多例子参考公众号:Python小例子

关闭warning的提示

import warnings
warnings.filterwarnings("ignore")

返回对象的帮助文档

help([object])#调用内置帮助系统
dir([object]) #会返回object所有有效的属性列表
vars([object]) #返回object对象的__dict__属性
type(object)#返回对象object的类型
hasattr(object, name)#用来判断name(字符串类型)是否是object对象的属性,若是返回True,否则,返回False
callable(object)#若object对象是可调用的,则返回True,否则返回False。注意,即使返回True也可能调用失败,但返回False调用一定失败。

python的三目运算

h = "变量1" if a>b else "变量2"

如何离线安装module

pip install Flask-WTF-0.10.0.tar.gz

利用pip升级全部的module

列出当前安装的包:

pip list

列出可升级的包:

pip list --outdate

升级一个包:

pip install --upgrade requests  // mac,linux,unix 在命令前加 sudo -H

升级所有可升级的包:

pip freeze --local | grep -v '^-e' | cut -d = -f 1  | xargs -n1 pip install -U

for i in `pip list -o --format legacy|awk '{print $1}'` ; do pip install --upgrade $i; done

排序中的技巧

 sorted(list, key=lambda k: XXXX)#根据key进行排序
 sort_index = numpy.argsort(list)#返回排序索引
sorted(range(len(lis)), key=lambda k: list[k])#返回排序索引

list中返回元素索引的函数

 a=[1,2,6]
 a.index(6)
 #2

for循环也可以和else结合

for i in range(5):
    print(i,end="\t")
else:
    print("完事了!")
#    0	1	2	3	4	完事了!

python输出之format的用法

https://www.cnblogs.com/lovejh/p/9201219.html

保存与读取变量

可以利用pickle包

import pickle

保存:
pickle.dump(list,open('tmp.txt', 'wb') ) 

读取:
list=pickle.load(open('tmp.txt', 'rb'))

原文链接:https://blog.csdn.net/sunflower_sara/article/details/80686867

try语句的应用

try:
     Normal execution block
except A:
     Exception A handle
except B:
     Exception B handle
except:
     Other exception handle
else:
     if no exception,get here
finally:
     print("finally")   

注意:else必须在finally之前,可有可无;finally必须放最后,也是可有可无;
else的代码必须是在执行了except:语句之后才执行,否则不执行;finally:的语句是无论如何都要执行的。
例子:

try:
    saefe('123')
except NameError:
    print("Get AError")
except:
    print("exception")
else:
    print("else")
finally:
    print("finally")
#Get AError
#finally

例子2:

try:
   a=1
except NameError:
    print("Get AError")
except:
    print("exception")
else:
    print("else")
finally:
    print("finally")
#else
#finally

在这里插入图片描述

ASCII与十进制的转化

chr(65)
#'A'
ord('A')
#65

reshape的用法

narray.reshape((n,m))#可以将narray改变为n行m列的narray,排列次序是逐行的
narray.reshape((-1,n))#将narray转化为n列的数组,同理也可以对行进行处理

list与np.array的转化

import numpy as np
a=np.arange(10)
a
#array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
b=a.tolist()
b
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
c=np.array(b)
c
#array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

list变成array:np.array(list)
list变成matrix:np.mat(list)
array和matrix相互转换:np.asmatrix( )和np.asarray( )
array变成list:data.tolist( )

ascii展示对象

ascii(类名)
#返回类中变量的赋值

判断对象是否具有某个属性

hasattr(object,'name')
#判断object是否具有name的属性,如果有返回True

eval()和exec()执行字符串中的代码

==eval()==可将字符串str当作有效的表达式来求值并返回计算结果取出字符串中的内容

def fun1(x):
    i=10
    return i+x

s="print(fun1(2))"
eval(s)
# 12

==exec()==函数也可以达到这样的效果:

def fun1(x):
    i=10
    return i+x

s="print(fun1(2))"
exec(s)
# 12

字符串连接

python中字符串连接可以使用+或者join函数,在连接两个字符串时用+很方便,但是连接多个字符串时用join函数效率更高。

a='python'
b='is'
c='easy'
d='to'
e='learn'
s=a+' '+b+' '+c+' '+d+' '+e
print(s)
#python is easy to learn

s2=' '.join((a,b,c,d,e))
print(s2)
#python is easy to learn

字符串大小写转化

str = "www.runoob.com"
print(str.upper())          # 把所有字符中的小写字母转换成大写字母
print(str.lower())          # 把所有字符中的大写字母转换成小写字母
print(str.capitalize())     # 把第一个字母转化为大写字母,其余小写
print(str.title())          # 把每个单词的第一个字母转化为大写,其余小写 
#WWW.RUNOOB.COM
#www.runoob.com
#Www.runoob.com
#Www.Runoob.Com

chain高效串联多个容器对象

from itertools import chain
a=[[1,5,5],2,3]
b=(5,6,8)
c=set([7,8,9])
for i in chain(a,b,c):
    print(i)
# [1, 5, 5]
# 2
# 3
# 5
# 6
# 8
# 8
# 9
# 7

合并多个字典

dic1={'a':1,'b':2}
dic2={'c':3}
dic3={'d':4}
{**dic1,**dic2,**dic3}
#{'a': 1, 'b': 2, 'c': 3, 'd': 4}

查看对象类型

type(object)

zip聚合迭代器

for x,y in zip(list1,list2):
	XXXXXX

zip还可以快速创建字典:

dict(zip(['a','b'],[1,2]))
# {'a': 1, 'b': 2}

全局变量和非局部变量的声明

global var: 将var声明为全局变量,用于函数内部,编译器会从最外部寻找var.

i=20
def fun1(x):
    i=10
    def fun2(x):
        global i
        i=i+x
        return i
    return fun2(x)
print(fun1(2))
# 22

nonlocal var:表示从上一层寻找var,而不是从最外寻找。

i=20
def fun1(x):
    i=10
    def fun2(x):
        nonlocal i
        i=i+x
        return i
    return fun2(x)
print(fun1(2))
# 12

四舍五入

round(x,ndigits)#ndigits表示小数点保留的位数

反向迭代器

reversed([1,4,2,5,1])

父子继承关系的鉴定

issubclass(objectA,objectB)
#判断objectA是不是objectB的子类,如果是返回True

用户输入

a=input('请输入 :')

groupy对字典字段进行分组

from itertools import groupby
a=[{'data':"1","weather":"cloud"},{"data":"2","weather":"sunny"},{'data':'3','weather':'cloud'}]
# groupby会把相邻的组合在一起,因此需要对a的字段进行排序
a.sort(key=lambda x: x['weather'])
for k, items in groupby(a,key=lambda x:x['weather']):
    print(k)
    for i in items:
        #注意这里items也是一个迭代器
        print('data is {}'.format(i['data']))

在这里插入图片描述

利用Counter函数统计频数

from collections import Counter
a=[1,5,6,8,7,8,"zou",9,6,1,2,5,4,5,4,"zou"]
res=Counter(a)
res

b=['zou',1,5]
res2=Counter(b)
res2
Res=res+res2
#对应频数可以相加
Res
Res['zou']

在这里插入图片描述

利用itemgetter实现多字段排序

from operator import itemgetter
a=[{'date':"1","weather":"cloud"},{"date":"2","weather":"sunny"},{'date':'3','weather':'cloud'}]
a.sort(key=itemgetter('weather','date'))

在这里插入图片描述

time模块的应用

import time
seconds=time.time()#获取此刻时间,返回浮点数
#1582366998.55335

local_time=time.localtime(seconds)
#time.struct_time(tm_year=2020, tm_mon=2, tm_mday=22, tm_hour=18, tm_min=23, tm_sec=18, tm_wday=5, tm_yday=53, tm_isdst=0)

str_time=time.asctime(local_time)
# 'Sat Feb 22 18:23:18 2020'

#格式化时间字符串,注意大小写
format_time=time.strftime('%Y-%m-%d %H:%M:%S',local_time)
# '2020-02-22 18:23:18'
# 	%Y  Year with century as a decimal number.
#     %m  Month as a decimal number [01,12].
#     %d  Day of the month as a decimal number [01,31].
#     %H  Hour (24-hour clock) as a decimal number [00,23].
#     %M  Minute as a decimal number [00,59].
#     %S  Second as a decimal number [00,61].
#     %z  Time zone offset from UTC.
#     %a  Locale's abbreviated weekday name.
#     %A  Locale's full weekday name.
#     %b  Locale's abbreviated month name.

#字符串转时间格式
t="2021-10-1"
date_list = time.strptime(t, "%Y-%m-%d")
# time.struct_time(tm_year=2021, tm_mon=10, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=274, tm_isdst=-1)

#从struct_time中提取具体年月日数值
y, m, d = date_list[:3]

#将数值转化为时间字符串
from  datetime import datetime
datetime(2022, 3, 5).strftime("%Y-%m-%d")
# '2022-03-05'
#或者直接用字符串连接函数
"-".join(("2022","3","5"))
# '2022-3-5'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值