当前位置: 移动技术网 > IT编程>脚本编程>Python > python 100例使用方法笔记

python 100例使用方法笔记

2020年07月08日  | 移动技术网IT编程  | 我要评论

进制编码相关

  • bin、oct、hex (十 >> 二、八、十六,有前缀)
  • int(‘11’, 2) (有前缀)或者 format(10, ‘b/o/x’)(无前缀)(二、八、十六 >> 十)
  • ord(‘a’) chr(97)
  • bytes(’ ', encoding=‘utf-8’) 字符串>>字节

数据结构

# 字典
dict(a='a',b='b')
dict(zip(['a','b'],[1,2]))
dict([('a',1),('b',2)])
set([1, 3, 2, 2])   {1, 2, 3}
tuple([1, 3, 2, 2]) (1, 3, 2, 2)
frozenset([1,1,3,2,3])  frozenset({1, 2, 3}) 没有add pop append等方法
a = [1,4,2,3,1]
a[slice(0, 5, 2)]      [1,2,1]

算术运算

divmod(10,3)    (3, 1) 元组,商和余数
pow(3,2) 幂运算
pow(3,2,4)  3、2幂运算后对4取余
round(1111.045, 2) 四舍五入,最后一位非零若是5则舍去了,很奇怪
round(1111.045, -2) 四舍五入 1100.0

在这里插入图片描述

常用函数

filter过滤器
x = [1, 2, 3, 5]
odd = filter(lambda e: e % 2, x)
for e in odd:  # 找到奇数
    print(e)

reduce(lambad p1,p2:p1*p2, [1, 2, 3], 4) 
map(func, [1,2,3])将func函数应用到列表的每一个元素
字典生成式,列表生成式
dict.get(value, [])  不存在键value,就返回[]
# 多行输出 使用一对三重引号
print('''"Oh no!" He exclaimed.
"It's the blemange!"''')

'abcd'.find('c') 返回下标
双引号 会忽略字符串中的转义字符
单引号 就需要加 斜杠
a = [1, 3, 4, 2, 1]
sorted(a,reverse=True)

a = [{'name':'xiaoming','age':18,'gender':'male'}, {'name':'xiaohong','age':17,'gender':'female'}]
sorted(a,key=lambda x: x['age'],reverse=False)  按年龄排序

sum([1,2], 1) 求和,指定初始值为1,结果为4

eval('[1,3,5]*3')  [1, 3, 5, 1, 3, 5, 1, 3, 5] 计算字符串型表达式的值

all([1,0,3,6])  False,可迭代对象的所有元素都为真,结果为真
any([0,0,1]) True

input() 获取输入

lst = [1]
print(f'lst:{lst}') lst:[1]    f打印
print('lst:{lst}') lst:{lst}
print('lst:{}'.format(lst))  format格式化打印

type()
 filter(lambda x: x>10,[1,11,2,45,7,6,13])  [11, 45, 13] 过滤器

1 < x < 3 链式操作
‘zifuchuan’.split(' ')
'zifuchuan'.replace('fu',  ',')
翻转字符串 s[::-1]   ''.join(reversed(s))

# 对时间的操作
import time
t = time.time()
# 1594021874.1056361
time_split = time.localtime(t) 年月日时分秒  周索引  年索引  夏令时?什么东西
# time.struct_time(tm_year=2020, tm_mon=7, tm_mday=6, tm_hour=15, tm_min=51, tm_sec=14, tm_wday=0, tm_yday=188, tm_isdst=0)
str_time = time.asctime(local_time) 时间结构体转字符串
# 'Mon Jul  6 15:51:14 2020'
format_time = time.strftime('%Y.%m.%d %H:%M:%S',local_time) # 时间结构体转指定格式时间字符串
# '2020.07.06 15:51:14'
time_structure = time.strptime(format_time,'%Y.%m.%d %H:%M:%S') # 时间字符串转时间结构体
# time.struct_time(tm_year=2020, tm_mon=7, tm_mday=6, tm_hour=15, tm_min=51, tm_sec=14, tm_wday=0, tm_yday=188, tm_isdst=-1)

from math import ceil
ceil(x)  the smallest integer >= x

装饰器

# property
class Student(object):
    @property
    def birth(self):
        return self._birth
    @birth.setter
    def birth(self, value):
        self._birth = value
	@birth.deleter
	def birth(self):
		del self._birth
    @property
    def age(self):
        return 2015 - self._birth
birth 可读可写可删除,age只可读
from functools import wraps
import time

def print_info(f):
    """
    @para: f, 入参函数名称
    """
    @wraps(f) # 确保函数f名称等属性不发生改变
    def info():
        print("调用 %s" % (f.__name__))
        t1 = time.time()
        f()
        t2 = time.time()
        delta = t2 - t1
        print("%s 函数执行时间为:%f s" % (f.__name__, delta))
    return info

@print_info
def f1():
    print('1')
    time.sleep(1)
    print('2')
f1()
结果:
调用 f1
1
2
f1 函数执行时间为:1.000388 s

先执行装饰器?
list() 会把迭代器中所有元素取出来
class YourRange():
    def __init__(self, start, end):
        self.value = start
        self.end = end

    # 成为迭代器类型的关键协议
    def __iter__(self):
        return self

    # 当前迭代器状态(位置)的下一个位置
    def __next__(self):
        if self.value >= self.end:
            raise StopIteration

        cur = self.value
        self.value += 1
        return cur
yr = YourRange(2, 5)
for e in yr:
    print(e)
yr就没有值了,迭代器空了,继续next(yr)会报错

画图

import matplotlib.pyplot as plt 
plt.plot([0, 1, 2, 3, 4, 5],
        [1.5, 1, -1.3, 0.7, 0.8, 0.9]
        ,c='red')
plt.bar([0, 1, 2, 3, 4, 5],
        [2, 0.5, 0.7, -1.2, 0.3, 0.4]
        )
plt.show()

在这里插入图片描述

import seaborn as sns
sns.barplot([0, 1, 2, 3, 4, 5],
        [1.5, 1, -1.3, 0.7, 0.8, 0.9]
        )
sns.pointplot([0, 1, 2, 3, 4, 5],
        [2, 0.5, 0.7, -1.2, 0.3, 0.4]
        )
plt.show()

在这里插入图片描述

# 会自动打开html
import plotly.graph_objs as go
import plotly.offline as offline

pyplt = offline.plot
sca = go.Scatter(x=[0, 1, 2, 3, 4, 5],
             y=[1.5, 1, -1.3, 0.7, 0.8, 0.9]
            )
bar = go.Bar(x=[0, 1, 2, 3, 4, 5],
            y=[2, 0.5, 0.7, -1.2, 0.3, 0.4]
            )
fig = go.Figure(data = [sca,bar])
pyplt(fig)

在这里插入图片描述

pyecharts 好像也挺不错

迭代器

def fibonacci(n):
	a, b = 1, 1
	for _ in range(n):
		yield a
		a, b = b, a+b
f = fibonacci(10)
list(f)   [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
for fib in fibonacci(10):
	print(fib)
from math import ceil

def divide_iter(lst, n):
    if n <= 1:
        return lst
    i, num = 0, ceil(len(lst) / n)
    while i < n:
        yield lst[i*num:(i+1)*num]
        i += 1
divide_iter([1, 2, 3, 4, 5], 3)  [[1, 2], [3, 4], [5]]
enumerate()
类中重写 __iter__ 使对象实例可迭代,返回一个迭代器iter()
iter() 创建迭代器

估计用不到的函数

import sys
a = [1, 2]
sys.getsizeof(a)  查看变量所占字节

import os
os.path.splitext('D:a.csv')  提取文件后缀名
os.path.split('D:a.csv') 提取文件名
os.chdir(path)
os.listdir()
# with执行结束会自动关闭文件
with open('drinksbycountry.csv',mode='r',encoding='utf-8') as o:
#o = open(file, mode='r', encoding='utf-8')  r只读  w只写  a追加  x非排他性创建
	content = o.read()
	w = o.write('shishang')  估计返回的是写入成功还是失败
	

import calendar
calender.isleap(2020)   True


# 动态操作对象的属性
# 如果对象有property装饰器,则 两个属性共存亡
getattr(xiaoming,'id')
delattr(xiaoming,'id')
hasattr(xiaoming,'id')
id(a)  查看变量内存地址
hash()  list dict set等可变对象不可哈希,自定义的实例都可以哈希
callable() 对象是否可被调用,需要对象实现__call__方法
isinstance(s, Student)
issubclass(Undergraduate, Student) 父子关系鉴定
dir(student)  查看student的所有变量、方法

本文地址:https://blog.csdn.net/qq_36537768/article/details/107155831

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网