Python面试100讲的基础知识

文章目录

1 导入Python模块,指定别名 from,import,as

import math
from math import * # 导入所有成员
import numpy as np # 指定别名为np

2 设置搜索路径export,.pth,sys.path.append()

方式:
1 设置Pythonpath环境变量
临时环境变量 export,.pth,sys.path.append() PYTHONPATH=添加的路径
win下 set PYTHONPATH=添加的路径

2 添加.pth文件
在Python安装目录,随便新建文件,后缀.pth, 在里面写入绝对路径,然后就可以直接调用路径下的所有文件


3 通过sys.path设置路径
import sys
sys.path.append(r"E:\admin\diskpart\201921050\12_python_lib\myfunction")

4 使用pycharm,可以设置搜索路径
# import working 
# # 这就是文件为working.py的函数, 
# # 该文件路径保存在abc.pth中
# print(working.hello())

# import sys
# sys.path.append(r"E:\admin\diskpart\201921050\12_python_lib\myfunction")
# import myfunction 
# # 该文件保存在"E:\admin\diskpart\201921050\12_python_lib\myfunction\myfunction.py")
# myfunction.hello_world("按个")
# print("hehh")

3 字符串连接 有5种方式+,"""",’,’,format,join

'''
1 str1+str2
2 直接连接 str1str2 s="hello""world"
3 逗号连接 print("hello", "world") 
4 格式化
s = '<%s><%s>'%(s1,s2)

5 join
s = ' '.join([s1,s2]) # 连接列表里面的两个字符串,中间用' '连接
'''
'\n1 str1+str2\n2 直接连接 str1str2 s="hello""world"\n3 逗号连接 print("hello", "world") \n4 格式化\ns = \'<%s><%s>\'%(s1,s2)\n\n5 join\ns = \' \'.join([s1,s2]) # 连接列表里面的两个字符串,中间用\' \'连接\n'

4 字符串与非字符串相连+,%,重定向

n=23
b = True
v = 12.44
s1 = "hello"
s = s1 + str(n) + str(v) + str(b)
print(s)

# 格式化
s = "<%s><%d><%.2f><%d>"%(s1,b,v,n)
print(s)

# 重定向
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print(s1,True,n,v,sep="*")
sys.stdout = old_stdout
result_str = result.getvalue()
print(result_str)

hello2312.44True
<hello><1><12.44><23>
hello*True*23*12.44

5 类显示字符串__str__(self):

class HelloWorld:
    def __str__(self):
        return "this is a balla"
h = HelloWorld()
print(h)
this is a balla

6 进制表示和转换 bin,int,hex,oct

# 不同表示
n1 = 1234 # 十进制
n2 = 0b1010 # 二进制
n3 = 0o123 # 八进制
n4 = 0xfa # 16进制
print(n1,n2,n3, n4)

# 转换
print(bin(10)) # 十进制转2进制
print(int(0b101), 2) # 各种进制转10进制,, 这里是2进制
print(hex(23)) # 转16进制
print(oct(23)) # 转八进制
1234 10 83 250
0b1010
5 2
0x17
0o27

7 字符串首字母大小写capitalize,upper,lower

s1 = "hello world"
print(s1.capitalize()) # 首字母大写

s2 = s1[0:1]+s1[1:3].upper()+s1[3:] # 字符串小写变大写
print(s2)

s1 = "Hello"
s3 = s1[0].lower() + s1[1:] # 变小写
print(s3)

# 每一个首字母都变大写
s4 = "this is a beauitful cat !"
new_str =' '.join([i.capitalize() for i in s4.split(" ")])
print(new_str)
Hello world
hELlo world
hello
This Is A Beauitful Cat !

8 检测字符串是否为数字isdigit,isalnum,isspace

s1 = '12345'
print("isdigit检测数字:",s1.isdigit())
s2 = '12345a'
print("12345a".isalnum()) #数字字母混合
print(' '.isspace()) # 是否空白
isdigit检测数字: True
True
True

9 字符串转化为整数,安全的

try:
    print(int("123a"))
except Exception as e:
    print(e)
invalid literal for int() with base 10: '123a'

10 字符串翻转 s1[::-1]

# 考察分片问题

# 1循环
s1 = "abcde"
for c in s1:
    s2 = c+s2
print(s2)

print(s1[0::2])  # 从0开始 步长为2
print(s1[::1]) # 字符串本身
print(s1[::-1]) # 字符串翻转
edcba12345a
ace
abcde
edcba

11 格式化整数format(1234,’>10d’)左对齐补

n = 1234
print(format(1234,'0>10d')) # 左侧补0
print(format(n,'0<10d'))  # 右侧补0

# 格式化浮点数,保留后两位小数点
f = 41.2569
print(format(f, '0.2f')) # 不足补0

# format函数
# 设置格式化规则
x2 = 12.1
print(format(x2, "*>15.4f")) # 右对齐,补* 小数点后4位
print(format(x2, "*<15.4f"))
print(format(x2, "#^15.4f")) # 中对齐
print(format(123456789, ',')) # 千位号分割
print(format(123214.1242, ',.2f'))
print(format(x2, "E"))
print(format(x2, "0.2E"))

0000001234
1234000000
41.26
********12.1000
12.1000********
####12.1000####
123,456,789
123,214.12
1.210000E+01
1.21E+01

12 字符串同时输出单双引号

print("'hk\' ahskg \asg")
print('"hello"    \'world\' ')
'hk' ahskg sg
"hello"    'world' 

13 转义符失效保持

print(r"let\'s go")  # r表示保留转义字符\
print(r'hello\nworld')

print("let\'s go'")
print(repr("let\'s go'"))  # repr跟r是一样的

print("保持多行 原格式输出")
print(
"""--
    hello
        world
""")
let\'s go
hello\nworld
let's go'
"let's go'"
保持多行 原格式输出
--
    hello
        world

14 print函数 sep="",end=""

print("aaa","bbbb", sep="**") # 增加中间的分隔符

# 不换行,首位相接
print("hello", end="*")
print("world")

# 格式化
print("长度是:%d,%s"%(256,"萨嘎"))
aaa**bbbb
hello*world
长度是:256,萨嘎

15 列表,元组,集合区别

# 去掉列表重复数据
# 列表和结合转换
# 集合和列表的区别

#列表 list
a = [1,2,3]
print(type(a), a)

#元组 tuple
b = (1,2,3,4,5)
print(type(b),b)

# 集合 set
c = {1,2,3,4,5}
print(type(c),c)
d = {1,2,2,3,4,2,5}
print(c==d)
'''
区别:
集合没有重复的元素
集合中的元素与顺序无关
'''
<class 'list'> [1, 2, 3]
<class 'tuple'> (1, 2, 3, 4, 5)
<class 'set'> {1, 2, 3, 4, 5}
True





'\n区别:\n集合没有重复的元素\n集合中的元素与顺序无关\n'

16 列表如何去重

a = [1,2,2,3,5,3]
a_res = list(set(a)) # 先转集合再转列表
print(a_res)
[1, 2, 3, 5]

17 集合的api add,remove,contains

a = {3,2,1}

# 添加
a.add(123)
print(a)
a.add("asg")
print(a)

# 删除
if a.__contains__("asg"):
    a.remove("asg")
    print("删除后:",a)
else:
    print("不存在")

{123, 1, 2, 3}
{1, 2, 3, 'asg', 123}
删除后: {1, 2, 3, 123}

18 集合中的运算 | ^ & union,intersection,difference

x1 = {1,2,3}
x2 = {2,3,4,5}
print(x1|x2) # 合并
print(x1.union(x2))

print(x1&x2) # 交集
print(x1.intersection(x2))

# x1中存在,x2不存在
print(x1.difference(x2))

# 排除x1, x2 
print(x1^x2)
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
{2, 3}
{2, 3}
{1}
{1, 4, 5}

19 列表连接 +,extend

a = [1,2,3]
b = [3,4,5]
print(a+b)
a.extend(b)
print(a)

'''
差异 +不改变列表值, 但是extend改变a列表
+ 必须两次同类型
extend 列表可以增加元组
list.extend(tuple)
'''
[1, 2, 3, 3, 4, 5]
[1, 2, 3, 3, 4, 5]





'\n差异 +不改变列表值, 但是extend改变a列表\n+ 必须两次同类型\nextend 列表可以增加元组\nlist.extend(tuple)\n'

20 列表顺序随机打乱, random.shuffle(a)

a = [1,2,3,4,5,6,7,9,10]
import random
from typing import*
def random_list(a:List):
    for i in range(0,100):
        index1 = random.randint(0,len(a)-1)
        index2 = random.randint(0,len(a)-1)
        a[index1],a[index2] = a[index2],a[index1]
random_list(a)
print(a)

# 直接调用API
a = [1,2,3,4,5,6,7,9,10]
random.shuffle(a)
print(a)

[7, 6, 4, 1, 3, 10, 5, 9, 2]
[10, 6, 4, 5, 2, 7, 3, 9, 1]

21 *运算符 可变参数,以元组形式导入, **字典

'''
作用
* 元组形式
'''
def fun1(para1, *para2,x): # para2是可变参数, *号参数只能有一个,以元组形式导入
    print(para1,)
    print(para2) # 这是四个元组
    print(x)
    
fun1(1,2,3,4,5, x=2)

def fun2(para1, **para2): # para2是可变参数, ** 以字典形式导入
    print(para1,)
    print(para2) 
fun2(1,a=2,b=3,c=4, x=2)
1
(2, 3, 4, 5)
2
1
{'a': 2, 'b': 3, 'c': 4, 'x': 2}

22 合并列表和字典,* **

# 列表 
a = [1,2,3]
b = [4,5,6]
print([*a, *b])

c = {"a":1, "b":2}
d = {"c":23, "d":90}
print({**c,**d})
[1, 2, 3, 4, 5, 6]
{'a': 1, 'b': 2, 'c': 23, 'd': 90}

23 快速调换字典中的key和value, set.items()

a = {"a":1, "b":2}
b = {v:k for k,v in a.items()}
print(b)
print(b[1])
{1: 'a', 2: 'b'}
a

24 0-100的列表

print([i for i in range(101)])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

25 两个列表或元组合并一个字典 dict(zip(a,b))

# zip dict 
a = ["a","b"]
b = [1,2]
#合并为字典
print(dict(zip(a,b))) #先压缩,在字典

fields = ('id', 'ame', 'age')
records = [['01','bill',20], ['02','jia',23]]
res = []
for record in records:
    res.append(dict(zip(fields,record)))
print(res)
{'a': 1, 'b': 2}
[{'id': '01', 'ame': 'bill', 'age': 20}, {'id': '02', 'ame': 'jia', 'age': 23}]

26 元组 字典 列表 集合差异

# 1 语法差异 () {} [] {,}
# 元组是只读的, 
# 列表是可写的
# 列表和元组的大小不同,列表分配内存块小, 
# 但是元组使用大的内存块,占用内存小, 大量元素时建议使用元组

27 列表方法 排序sort(reverse=),sorted()

a = [1,2,32,5,3]
a.sort(reverse=True)  # 从小到大, 自身排序
print(a)
a = [1,2,32,5,3]
b = sorted(a,reverse=False) # 新建排序, 默认是正序,False
print(b)

'''
区别sort 属于列表方法
sorted属于独立函数

sort改变列表本身
sorted返回
'''
[32, 5, 3, 2, 1]
[1, 2, 3, 5, 32]





'\n区别sort 属于列表方法\nsorted属于独立函数\n\nsort改变列表本身\nsorted返回\n'

28 列表对象如何排序 str(self): lt(self, other):

class Myclass:
    def __init__(self):
        self.value = 0
    def __str__(self):
        return "Myclass"
    def __lt__(self, other): #用于判断大小的特征
        return self.value < other.value
    
my1 = Myclass()
my1.value = 20

my2 = Myclass()
my2.value = 10

my3 = Myclass()
my3.value = 30

print(my1)  # 测试def __str__(self):

a = [my1, my2, my3]
print(a)

a.sort(reverse = False)
print(a[0].value)
Myclass
[<__main__.Myclass object at 0x000002F63C39A240>, <__main__.Myclass object at 0x000002F63C39A2E8>, <__main__.Myclass object at 0x000002F63C39A2B0>]
10
# 列表对象如何排序
class Myclass:
    def __init__(self):
        self.value = 0  
my1 = Myclass()
my1.value = 20

my2 = Myclass()
my2.value = 10

my3 = Myclass()
my3.value = 30


a = [my1, my2, my3]
print(a)

import operator 

a.sort(reverse = False, key=operator.attrgetter('value'))
print(a[0].value)
print(a[1].value)
print(a[2].value)
[<__main__.Myclass object at 0x000002F63C39A208>, <__main__.Myclass object at 0x000002F63C39A438>, <__main__.Myclass object at 0x000002F63C39A400>]
10
20
30

29 删除,增加列表 pop del append

a = [4,2,5,6]
print(a)
del a[2]
print(a)

print(a.pop(1))
print(a)
[4, 2, 5, 6]
[4, 2, 6]
2
[4, 6]

30 使用lambda进行列表排序sorted(d, key = lambda x:x[‘age’])

d = [
    {'nama':'zq', "age":23},
    {'nama':'ji', "age":26},
    {'nama':'zw', "age":18},
]
print(d)
print(sorted(d, key = lambda x:x['age'])) #lambda传入的参数是 
[{'nama': 'zq', 'age': 23}, {'nama': 'ji', 'age': 26}, {'nama': 'zw', 'age': 18}]
[{'nama': 'zw', 'age': 18}, {'nama': 'zq', 'age': 23}, {'nama': 'ji', 'age': 26}]

31 字典key的类型

# 列表和字典本身
d = {}
d['name'] = 'Biill'
d[True] = False
d[12.3] = 322
d[(1,2,3)] = [3,4,5]

class Person:
    pass
p1 = Person()
p2 = Person()

d[p1] = "p1"
d[p2] = 'p2'

print(d)

# 下面是错误的,因为key是不能变的,但是列表和字典是可变的
# d[[1,2,3]] =3
# d[{'a':3}] =4
{'name': 'Biill', True: False, 12.3: 322, (1, 2, 3): [3, 4, 5], <__main__.Person object at 0x000002F63C383588>: 'p1', <__main__.Person object at 0x000002F63C383198>: 'p2'}

32 切片获取列表的部分元素gen = iter(range(10)) # 产生器

gen = iter(range(10)) # 产生器
print("怀孕已经完成")
print(type(gen))
for i in gen:
    print(i)
print("iteration孩子已经生产完毕,无法继续生产")    
for i in gen:
    print(i)
print("求放过,孩子已经生完了")
# 切片获取列表的部分元素
from itertools import islice
gen = iter(range(10))
print(type(gen))
for i in islice(gen,2,6): # 方法islicc切割
    print(i)
print("孩子已经通过大夫islice生产了2,3,4,5了, 而0,1被其杀死了,为了生产2,3,4,5")
for i in gen:
    print(i)
print("好了现在都生出来了,死了俩")
怀孕已经完成
<class 'range_iterator'>
0
1
2
3
4
5
6
7
8
9
iteration孩子已经生产完毕,无法继续生产
求放过,孩子已经生完了
<class 'range_iterator'>
2
3
4
5
孩子已经通过大夫islice生产了2,3,4,5了, 而0,1被其杀死了,为了生产2,3,4,5
6
7
8
9
好了现在都生出来了,死了俩

33 列表变成产生器

a = [i for i in range(10)]
print(a)
for i in a:
    print(i)
    
# 新建产生器
# 将列表的形式变成元组的形式就能够变成了一个产生器,产生器只是怀孕还未生产
b = (i for i in range(10)) # 有for 所以是一个产生器,但是没有for就是一个元组
print(b)
for i in b:
    print(i)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
1
2
3
4
5
6
7
8
9
<generator object <genexpr> at 0x000002F63C37F410>
0
1
2
3
4
5
6
7
8
9

34 字典与字符串中间的转换 json.dumps和loads

# json
import json
d = {'a':23,'b':33,'c':89}
json_str = json.dumps(d) #带s的dump将字典转化为str形式
print(json_str)
print(type(json_str))

# 将str的字典格式转化为dict
d1 = json.loads(json_str)
print(d1)
print(type(d1))

{"a": 23, "b": 33, "c": 89}
<class 'str'>
{'a': 23, 'b': 33, 'c': 89}
<class 'dict'>

35 字符串格式化方法:from string import Template

# 多少种
'''
%格式化
魔板字符串
字符串format方法
fstring

通过template对象封装,
$ 放置一些占位符
通过substitute方法用实际值替换占位符
'''
from string import Template
template1 = Template("$d is a beautiful code, $s is easy function, 功能强大")
print(template1.substitute(d = "python", s="zjq"))
data = {}
data['d'] = "zjjj"
data["s"] = "askksk"
print(template1.substitute(data))

template2 = Template("$hello world")
print(template2.substitute(hello = "abc"))
template3 = Template("${h}ello world $$  ")
print(template3.substitute(h = "abc"))


python is a beautiful code, zjq is easy function, 功能强大
zjjj is a beautiful code, askksk is easy function, 功能强大
abc world
abcello world $  

36 fstring格式化 f"string"中f起到的作用

# 直接使用变量
name = "zjq"
age = 20
def hello():
    print("hello")
s = f"my name is {name}, 我今年{age}岁, {hello()}"  # f表示有变量,或者函数
print(s)
hello
my name is zjq, 我今年20岁, None

37 字符串相关操作 len,max,[::]

str1 = "hello world, my name is zjq!"
print(str1[0:6])
print(str1[::-1]) # 全部翻转
print(str1[::2])
print(2*str1) # 打印两遍

print('b' in str1)
print('w' not in str1)

print(len(str1))
print(max(str1))
print("小",min(str1))
hello 
!qjz si eman ym ,dlrow olleh
hlowrd ynm szq
hello world, my name is zjq!hello world, my name is zjq!
False
False
28
z
小  

38 format 使用{}指定需要替换的数据

s1 = "Today is {}, the temperature is {},"
print(s1.format("saturday", 24))

s1 = "Today is {day}, the temperature is {degree},"
print(s1.format(day = "saturday",degree = 30))

class Person:
    def __init__(self):
        self.age = 20
    def get_name():
        return "bill"
s2 = "name is {name.age}"
print(s2.format(name = Person()))
Today is saturday, the temperature is 24,
Today is saturday, the temperature is 30,
name is 20

39 字符串居中显示 ‘<{:#^30}>’.format(s1)

s1 = "saga"
print("<"+s1.center(30) + ">")
print("<"+s1.center(30,'#') + ">")

print('<{:^30}>'.format(s1))
print('<{:#^30}>'.format(s1))
<             saga             >
<#############saga#############>
<             saga             >
<#############saga#############>

40 字符串列表连接 " # ".join(a)

s1 = "hello"
s2 = "world"
a  =  [s1,s2]
print(" # ".join(a))
hello # world

41 正则表达式 match, search

import re # 正则表达式
print(re.match('hello', 'hello'))
s1 = "Today is 2019-12-12"
m = re.match(".*\d{4}-\d{2}-\d{2}",s1)
if m is not None:
    print(m.group())
<_sre.SRE_Match object; span=(0, 5), match='hello'>
Today is 2019-12-12
# match 用于匹配
# search: 搜索
import re
m = re.match('.*python', 'i love python')
print(m)
m2 = re.search("python", "i love python")
print(m2)
<_sre.SRE_Match object; span=(0, 13), match='i love python'>
<_sre.SRE_Match object; span=(7, 13), match='python'>

42 搜索手机号 限定11位re.search

m = re.search('1\d{10}', 'wode shouj is 13096908985')
if m is not None:
    print(m.group())
    print(m.start())
    print(m.end())
13096908985
14
25

43 搜索区号 分机号 电话号

# 搜索区号 分机号 电话号
# 区号 3位 电话号至少7位 分机号至少3位 024-2356897-231
# 正则表达式的分组
import re
m = re.search('\d{3}-\d{7,}-\d{3,}',"我的公司座机号码是: 024-123456789-259")
if m is not None:
    print(m.group())
    print(m.groups())
#     print(m.groups()[0])
#     print(m.groups()[1])
#     print(m.groups()[2])
024-123456789-259
()

44 查找所有的email re.findall(prefix + ‘com’ + prefix + ‘net’, s, re.I)

import re
s = 'wode emal地址是[email protected],你的是[email protected]'
prefix = '[0-9a-zA-Z]+@[0-9a-zA-Z]+\.'
res = re.findall(prefix + 'com' + prefix + 'net', s, re.I)# re.I表示忽略大小写
print(res)
[]

45 浮点数浮点数正则表达

# 浮点数浮点数正则表达式 -?\d+(\.\d+)? 完整浮点数  #     \d+任意多数字
import re
# 使用##替换浮点数
res = re.subn("-?\d+(\.\d+)?", '##', 'PI is 3.141592654, e is 2.71828 -0.2+1.3=1.1')
print(res) # ('PI is ##, e is ## ##+##=##', 5)
print(res[0])

# 动态替换
def fun(matched):
    return "<" + matched.group() + ">"
res = re.subn("-?\d+(\.\d+)?", fun, 'PI is 3.141592654, e is 2.71828 -0.2+1.3=1.1')
print(res) # ('PI is <3.141592654>, e is <2.71828> <-0.2>+<1.3>=<1.1>', 5)
print(res[0])

print("动态替换")
# 动态替换
def fun(matched):
    return format(float(matched.group()),"0.2f")
res = re.subn("-?\d+(\.\d+)?", fun, 'PI is 3.141592654, e is 2.71828 -0.2+1.3=1.1')
print(res) # ('PI is 3.14, e is 2.72 -0.20+1.30=1.10', 5)
print(res[0])
('PI is ##, e is ## ##+##=##', 5)
PI is ##, e is ## ##+##=##
('PI is <3.141592654>, e is <2.71828> <-0.2>+<1.3>=<1.1>', 5)
PI is <3.141592654>, e is <2.71828> <-0.2>+<1.3>=<1.1>
动态替换
('PI is 3.14, e is 2.72 -0.20+1.30=1.10', 5)
PI is 3.14, e is 2.72 -0.20+1.30=1.10

46 提取url搜索re.findall

import re
s = '<a href="https://baidu.com">饥渴</a>  <a href="https://wr.com">计科</a> '

res = re.findall('<a[^>]*href="([^>]*)">',s,re.I) #[^>]* 除了>  ()表示group
print(res)
['https://baidu.com', 'https://wr.com']

47 去读xml数据,字典

'''
xml格式
'''
# 去读xml文件,属性
from xml.etree.ElementTree import parse
doc = parse('files/products.xml')
print(type(doc))
for item in doc.iterfind('products/product'): # 过滤所有products 里面的
    id = item.findtext('id')
    name = item.findtext('name')
    price = item.findtext('price')
    uuid = item.get('uuid') # 当前节点的属性
    
    print('uuid','=',uuid)
    print('id','=',id)
    print('name','=',name)
    print('price','=',price)
    print('---------')
<class 'xml.etree.ElementTree.ElementTree'>
uuid = 1234
id = 10000
name = iPhone9
price = 9999
---------
uuid = 4321
id = 20000
name = 特斯拉
price = 800000
---------
uuid = 5678
id = 30000
name = Mac Pro
price = 40000
---------

48 字典转换为xml

import dicttoxml
import os
from xml.dom.minidom import parseString
d = [20,"names",
     {'name':'ball','age':20, 'salary':2000},
     {'name':'zjq', 'age':56, 'salary':1253},]
bxml = dicttoxml.dicttoxml(d, custom_root='persons') # 后面的参数是xml根节点
xml = bxml.decode('utf-8')
print(xml)
 
dom = parseString(xml)
pretty_xml = dom.toprettyxml(indent='  ')
print(pretty_xml)
with open("my_file/person1.xml", 'w', encoding='utf-8') as fd:
    fd.write(pretty_xml)
    
<?xml version="1.0" encoding="UTF-8" ?><persons><item type="int">20</item><item type="str">names</item><item type="dict"><name type="str">ball</name><age type="int">20</age><salary type="int">2000</salary></item><item type="dict"><name type="str">zjq</name><age type="int">56</age><salary type="int">1253</salary></item></persons>
<?xml version="1.0" ?>
<persons>
  <item type="int">20</item>
  <item type="str">names</item>
  <item type="dict">
    <name type="str">ball</name>
    <age type="int">20</age>
    <salary type="int">2000</salary>
  </item>
  <item type="dict">
    <name type="str">zjq</name>
    <age type="int">56</age>
    <salary type="int">1253</salary>
  </item>
</persons>
import xmltodict
import dicttoxml
import os
from xml.dom.minidom import parseString
import pprint
with open("my_file/person1.xml", 'r', encoding='utf-8') as fd:
    xml = fd.read()
    d = xmltodict.parse(xml)
    print(d)
    pp = pprint.PrettyPrinter(indent= 4)
    pp.pprint(d)
    print(type(d))
OrderedDict([('persons', OrderedDict([('item', [OrderedDict([('@type', 'int'), ('#text', '20')]), OrderedDict([('@type', 'str'), ('#text', 'names')]), OrderedDict([('@type', 'dict'), ('name', OrderedDict([('@type', 'str'), ('#text', 'ball')])), ('age', OrderedDict([('@type', 'int'), ('#text', '20')])), ('salary', OrderedDict([('@type', 'int'), ('#text', '2000')]))]), OrderedDict([('@type', 'dict'), ('name', OrderedDict([('@type', 'str'), ('#text', 'zjq')])), ('age', OrderedDict([('@type', 'int'), ('#text', '56')])), ('salary', OrderedDict([('@type', 'int'), ('#text', '1253')]))])])]))])
OrderedDict([   (   'persons',
                    OrderedDict([   (   'item',
                                        [   OrderedDict([   ('@type', 'int'),
                                                            ('#text', '20')]),
                                            OrderedDict([   ('@type', 'str'),
                                                            (   '#text',
                                                                'names')]),
                                            OrderedDict([   ('@type', 'dict'),
                                                            (   'name',
                                                                OrderedDict([   (   '@type',
                                                                                    'str'),
                                                                                (   '#text',
                                                                                    'ball')])),
                                                            (   'age',
                                                                OrderedDict([   (   '@type',
                                                                                    'int'),
                                                                                (   '#text',
                                                                                    '20')])),
                                                            (   'salary',
                                                                OrderedDict([   (   '@type',
                                                                                    'int'),
                                                                                (   '#text',
                                                                                    '2000')]))]),
                                            OrderedDict([   ('@type', 'dict'),
                                                            (   'name',
                                                                OrderedDict([   (   '@type',
                                                                                    'str'),
                                                                                (   '#text',
                                                                                    'zjq')])),
                                                            (   'age',
                                                                OrderedDict([   (   '@type',
                                                                                    'int'),
                                                                                (   '#text',
                                                                                    '56')])),
                                                            (   'salary',
                                                                OrderedDict([   (   '@type',
                                                                                    'int'),
                                                                                (   '#text',
                                                                                    '1253')]))])])]))])
<class 'collections.OrderedDict'>

49 json文件映射为对象product = json.loads(json_str, object_hook=Product)

# 读取, 转化为Python对象
# self.__dict__ 的重要意义
class Product:
    def __init__(self, d):
        self.__dict__ = d

import json
with open(r"files/product.json", 'r') as fd:
    json_str = fd.read()
    print(json_str)
    product = json.loads(json_str, object_hook=Product) 
    # 这样就将json里面的dict转到类
    print(product.name)
    print(product.price)
    print(product.count)
    
    print("using def")
    def json2product(d):
        return Product(d)
    product1 = json.loads(json_str,object_hook=json2product)
    print(product1.name)
    print(product1.price)
    
{"name":"iPhone9",
"price":9999,
"count":3000}
iPhone9
9999
3000
using def
iPhone9
9999
# dumps用法
# python对象转json字符串
class Product:
    def __init__(self, name, price, count):
        self.name = name
        self.price = price
        self.count = count
product = Product("zjq", 10000,23) # 创建对象,保存到json文件中
def product2dict(obj):
    return {
        'name':obj.name,
        'price':obj.price,
        'count':obj.count
    }
json_str = json.dumps(product,default=product2dict,ensure_ascii=False)
print(json_str)

{"name": "zjq", "price": 10000, "count": 23}
# json dumps 多个对象
with open(r"files/products.json", 'r',encoding='utf-8') as fd:
    json_str = fd.read()
    print(json_str)
    
    # 加载为对象
    class Product:
        def __init__(self, d):
            self.__dict__ = d
    products = json.loads(json_str, object_hook=Product)
    print(products)
    for product in products:
        print(product.name)
        
    # 转化为json文件
    json_str = json.dumps(products, default=product2dict, ensure_ascii=False)
    print(type(json_str))
[
    {
    "name":"iPhone9",
    "price":9999,
    "count":3000},
    
	{"name":"特斯拉",
	"price":800000,
	"count":122}
]
[<__main__.Product object at 0x000002F63C439780>, <__main__.Product object at 0x000002F63C439B70>]
iPhone9
特斯拉
<class 'str'>

50 SQlite 数据库表

# 创建SQlite 数据库表 sqlite3是Python自带的数据库
import sqlite3
import os
path_db = 'data.sqlite'
if not os.path.exists(path_db):
    conn = sqlite3.connect(path_db) # 不存在就创建
    c = conn.cursor()
    c.execute('''create table persons
            (id int primary key not null,
            name text not null,
            age int not null,
            address char(100),
            salary real
            );''')
    conn.commit()
    conn.close()
    print("创建从数据库成功")
    
# 插入数据
with sqlite3.connect(path_db) as conn:
    c = conn.cursor()
    c.execute('delete from persons') # 删除table中person
    c.execute('''insert into persons(id,name,age,address,salary)
    values(1,'ball',32, 'caifornia',20000)''')
    c.execute('''insert into persons(id,name,age,address,salary)
    values(2,'zjq',30, 'caifornia',25000)''')
    c.execute('''insert into persons(id,name,age,address,salary)
    values(3,'rqx',18, 'beauuif',90000)''')
    conn.commit() # 必须含有这个才真正插入了,不然是调入缓存了
    print("insert success")
    
    pass

# 查询
with sqlite3.connect(path_db) as conn:
    c = conn.cursor()
    persons = c.execute('select name,age,address,salary from persons order by age')
    print(type(persons))
    res = []
    for person in persons:
        value= {}
        value["name"] = person[0]
        value["age"] = person[1]
        value["address"] = person[2]
        value["salary"] = person[3]
        res.append(value)
    print(res)
insert success
<class 'sqlite3.Cursor'>
[{'name': 'rqx', 'age': 18, 'address': 'beauuif', 'salary': 90000.0}, {'name': 'zjq', 'age': 30, 'address': 'caifornia', 'salary': 25000.0}, {'name': 'ball', 'age': 32, 'address': 'caifornia', 'salary': 20000.0}]
# ORM框架
'''
常用框架和区别
SQLALchemy: 偏向于SQL  灵活提交SQL语句
SQLobject:  面向对象更加,无法free 原生的SQL语句

'''
'\n常用框架和区别\nSQLALchemy: 偏向于SQL  灵活提交SQL语句\nSQLobject:  面向对象更加,无法free 原生的SQL语句\n\n'

51 read, readline,readlines

# 综合知识
# read readline readlines
with open(r"files/readme.txt",'r+',encoding="utf-8") as fd:
    # print(fd.read())  #读取全部
    # print(fd.read(3))  #读取前3个字符
    fd.seek(6) # 将文件指针向后6位,
    print(fd.read(3))# 从后六位之后读取三个打印出来
    pass

with open(r"files/readme.txt",'r+',encoding="utf-8") as fd:
    print("realine======\n",fd.readline())
    print("realine======\n",fd.readline(2)) #读取当前行 前两个字符
    
with open(r"files/readme.txt",'r+',encoding="utf-8") as fd:
    print("----")
    # print(fd.readlines(12)) # 第二行在12个字符之前,所以读取前两行
    print(fd.readlines())
    


你好,
realine======
 hello 你好,世界

realine======
 I 
----
['hello 你好,世界\n', 'I love you.\n', 'How are you? aaaaablbjljlsa\n']

52 json 序列化日期类型

# json 序列化日期类型
# 可以处理的数据类型 str int list tuple dict bool None
# datatime不支持json序列化
import json
from datetime import datetime,date
class Data2json(json.JSONEncoder):
    def default(self,obj):
        if isinstance(obj,datetime):
            return obj.strftime("%Y %m %d, %H %M %S")
        elif isinstance(obj,date):
            return obj.strftime("%Y %m %d")
        else:
            return json.JSONEncoder.default(self, obj)
d = {'name':"bill", "date":datetime.now()}
print(json.dumps(d,cls = Data2json,ensure_ascii=False))

{"name": "bill", "date": "2020 02 05, 20 37 04"}

53 读文件,统计字符,得到最多

# 算法
with open("files/readme.txt", 'r',encoding='utf-8') as fd:
    data = fd.read()
print(data)

d = {} # key 统计出现的字符 value统计总次数
max_char = ""
for c in data:
    if c.isspace():
        continue
    if d.get(c) is None:
        d[c] = 1
        if max_char == '':
            max_char = c
    else:
        d[c] += 1
        if d[max_char] < d[c]:
            max_char = c
print(max_char, d[max_char])
    
def get_max_char(data):
    d = {}
    max_char = ''
    for c in data:
        if c.isspace():
            continue
        if c not in d:
            d[c] = 1
            if max_char == '':
                max_char = c
        else:
            d[c] += 1
            if d[max_char] < d[c]:
                max_char = c
    print(f"最多的字符{max_char},有{d[max_char]}个")
get_max_char(data)
hello 你好,世界
I love you.
How are you? aaaaablbjljlsa

a 7
最多的字符a,有7个

54 装饰器的作用

'''
装饰器是一个函数,
经常用于插入日志等功能,性能测试,缓存处理

'''

# 自定义装饰器, 可以用来控制函数是否调用,完全控制函数
from functools import wraps
def log(lable,flag):
    def decorate(func):
        @wraps(func)
        def _wrap(*args,**kwargs):
            try:
                if flag: func(*args,**kwargs) #为真时调用函数
                print(f'name {func.__name__}')
            except Exception as e: print(e.args)
        return _wrap
    return decorate

@log("info",False)
def add(a,b,c):
    print(f"sum={a+b+c}")

add(1,2,3)

name add

55 判断调用的是函数还是方法MethodType, FunctionType

# 函数独立,但是方法需要类里定义
# isinstance
from types import MethodType, FunctionType

class MyClass:
    def process(self):
        pass
def process():
    pass
print(type(MyClass().process).__name__ == FunctionType)
print(type(MyClass().process))
print(type(process))

print(isinstance(MyClass().process, FunctionType))
print(isinstance(MyClass().process, MethodType))
print("-------")
print(isinstance(process, FunctionType))
print(isinstance(process, MethodType))
False
<class 'method'>
<class 'function'>
False
True
-------
True
False

56 声明静态方法 @staticmethod@classmethod

'''
共同点:
都是用来声明静态方法的。类名.方法名

1. @staticmethod不需要表示自身对象的self和自身类的cls参数,就像普通函数一样定义
2. @classmethod也不需要self参数,但第2个参数需要是表示自身的cls参数。避免硬编码。

'''
class MyClass:
    bar = 1 #静态变量,不需要实例化就可以调用
    def __init__(self):
        self.count = 20

    def process(self):
        print('process:',self.count)
    @staticmethod
    def static_process():
        print('static_process')
        print(MyClass.bar) # 直接不需要实例化调用
    @classmethod
    def class_process(cls): # 第一个参数表示是类本身参数
        print('class_process')
        print("cls.bar",cls.bar)
        print("cls",cls)
        cls().process()
        print("cls().count",cls().count)

print(MyClass.bar)
MyClass.static_process()
MyClass.class_process()
MyClass.bar = 123
MyClass.static_process()
1
static_process
1
class_process
cls.bar 1
cls <class '__main__.MyClass'>
process: 20
cls().count 20
static_process
123

57 元类

# 元类
# metaclass:元类, 创建类的魔板, 所有类都是通过他创建的,可以自由的控制类的创建过程
# 单例模式
class SingleTon(type):
    def __init__(self, *args, **kwargs):
        print('in __init__')
        self.__instance = None
        super(SingleTon, self).__init__(*args, **kwargs)
    def __call__(self, *args, **kwargs):
        print('in call')
        if self.__instance is None:
            self.__instance = super(SingleTon, self).__call__(*args, **kwargs)
            print(type(self.__instance))
        return self.__instance
class MyClass(metaclass=SingleTon):
    pass
my1 = MyClass()
my2 = MyClass()
print(my1 == my2)

    

in __init__
in call
<class '__main__.MyClass'>
in call
True

58 对象属性处理hasattr, getattr, setattr

'''
hasattr: 判断一个对象是否包含一个属性
getattr:获得一个对象属性值
setattr:设置
'''
class Person:
    def __init__(self):
        self.name = 'bill'
        self.age = 12
    def show(self):
        print(self.name)
        print(self.age)
if hasattr(Person, "show"):
    print("存在show方法")
    
person = Person()
setattr(person,"sex", '男')
setattr(person,'age',23)
print(getattr(person, "sex"))
print(getattr(person, "age"))
print(getattr(person, "name"))


存在show方法
男
23
bill

59 lambda表达式

# lambda表达式, 就是一个匿名函数,可以作为参数值传给函数或者方法
import re
a = [('a',1),('b',2),('c',3),('d',4),('e',5)]
a_1 = list(map(lambda x:x[0],a)) # map映射函数
a_2 = list(map(lambda x:x[1],a))
print(a_1)
print(a_2)


['a', 'b', 'c', 'd', 'e']
[1, 2, 3, 4, 5]

60 复制深层对象 copy与deepcopy的区别

# copy:复制深层对象引用
# deepcopy:复制深层对象的本身

import copy
a = [12,3,4,5,['a','b']]
c = copy.copy(a) #浅拷贝
d = copy.deepcopy(a) # 深拷贝
print(c,'\n',d)


print("a增加一个数据,但是c,d不会有变化")
a.append(23)
print(a)
print(c,'\n',d)

a[4][0] = 'xafa'
print("修改后,浅拷贝:",c) # 浅拷贝拷贝引用,当修改内值时,是会跟着源进行改变
print("修改后,深拷贝:",d) # 深拷贝拷贝本身,但是
[12, 3, 4, 5, ['a', 'b']] 
 [12, 3, 4, 5, ['a', 'b']]
a增加一个数据,但是c,d不会有变化
[12, 3, 4, 5, ['a', 'b'], 23]
[12, 3, 4, 5, ['a', 'b']] 
 [12, 3, 4, 5, ['a', 'b']]
修改后,浅拷贝: [12, 3, 4, 5, ['xafa', 'b']]
修改后,深拷贝: [12, 3, 4, 5, ['a', 'b']]

61 生成器,二维列表变成一维列表

'''
生成器yield
'''
def my_generator():
    num_list = [1,2,3,4,5,6]
    for num in num_list:
        yield num # 迭代
        
for num in my_generator():
    print(num,)

'''
[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
[1,2,3,4,5,6,7,8,9,10...]
'''
def enum_list(nested_list):
    for sub_list in nested_list:
        for element in sub_list:
            yield element
            
list1 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
for num in enum_list(list1):
    print(num,end=" ")
print()
print(list(enum_list(list1)))
1
2
3
4
5
6
1 2 3 4 5 6 7 8 9 10 11 12 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

62 递归生成器,多维转1维

from typing import List
nested_list = [4,[1,2,[4,5,6,[2,3,5],23],[2,2,435]]]
print(nested_list)
def enum_list(nested_list:List):
    try:
        for sub_list in nested_list:
            for element in enum_list(sub_list):
                yield element
    except TypeError:
        yield nested_list # 迭代单个
    pass

print(list(enum_list(nested_list)))
[4, [1, 2, [4, 5, 6, [2, 3, 5], 23], [2, 2, 435]]]
[4, 1, 2, 4, 5, 6, 2, 3, 5, 23, 2, 2, 435]

63 当前时间确定调用time.localtime(time.time())

import time
localtime = time.localtime(time.time())
print(localtime)
print(localtime.tm_year)
print(localtime.tm_mon)
print(localtime.tm_mday)
print(list(localtime))


time.struct_time(tm_year=2020, tm_mon=2, tm_mday=5, tm_hour=20, tm_min=37, tm_sec=4, tm_wday=2, tm_yday=36, tm_isdst=0)
2020
2
5
[2020, 2, 5, 20, 37, 4, 2, 36, 0]

64 保留字

import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

65 数字类型

int (整数),1, 只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。
bool (布尔),Truefloat (浮点数),1.233E-2
complex (复数),1 + 2j1.1 + 2.2j

66 空行

'''
函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。

空行与代码缩进不同,空行并不是Python语法的一部分。书写时不插入空行,Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构。

记住:空行也是程序代码的一部分。
'''
'\n函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。\n\n空行与代码缩进不同,空行并不是Python语法的一部分。书写时不插入空行,Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构。\n\n记住:空行也是程序代码的一部分。\n'

67 map()内置函数 用于映射

# map() 会根据提供的函数对指定序列做映射
c = list(map(chr, [66, 53, 0, 94]))
print(c)

def sq(x):
    return x**2
a1 = list(map(sq,[1,3,5]))
print(a1)
['B', '5', '\x00', '^']
[1, 9, 25]

68 内置函数reduce()问题

from functools import reduce
a = reduce (lambda x,y:x+y+2, [1,2,3,4,5])
print(a)

weights = [0.0 for i in range(3)]
print(weights)

weights = [0.0] * 5	#		=>[0.0 ,0.0 ,0.0 ,0.0 ,0.0]
print(weights)
23
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]

69 zip()函数的使用

input_vecs = [[1,1], [1,0], [0,1], [0,0]];
labels = [1,0,0,0];
zip1 = zip(input_vecs,labels)
#print (len(zip1))
print(list(zip1))

zip2 = zip(labels, input_vecs)
print(dict(zip2))
[([1, 1], 1), ([1, 0], 0), ([0, 1], 0), ([0, 0], 0)]
{1: [1, 1], 0: [0, 0]}

70 matplotlib画图

#首先插入matplotlib
#命令是 pip install matplotlib
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
x = np.linspace(0,10,100)
y_1 = x**3 + 10
plt.plot(x,y_1)
plt.show()

在这里插入图片描述

发布了97 篇原创文章 · 获赞 18 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_32460819/article/details/104188528