
- 一、数据类型和变量
- 二、字符串和编码
- 三、数据结构
- 1.list
- 2.tuple
- 3.dict
- 4.set
- 四、切片
- 五、循环分支
- 六、函数
- 七、迭代
- 八、列表生成式
- 九、生成器
- 十、高阶函数
- 十一、匿名函数
- 十二、面向对象编程
- 十三、文件 *** 作
- 十四、os模块
- 十五、json模块
- 十六、正则表达式
- 十七、datetime
- 十八、collections
- 十九、pillow
- 二十、requests
- 二十一、运算符
# 1.十六进制表示
if 0x10 == 16:
print("0x10 == 16") #
else:
print("0x10 != 16")
# 2.下划线数据表示
if 100_000_000.5 == 100000000.5:
print("100_000_000.5 == 100000000.5") #
else:
print("100_000_000.5 != 100000000.5")
# 3.科学计数法
if 1e8 == 100000000:
print("1e8 == 100000000") #
else:
print("1e8 != 100000000")
# 4.取消字符串转义
print(r"\n \t )"# \n \t # 5.布尔值与逻辑运算 print
(
TrueandFalse ) # Falseprint (
TrueorFalse ) # Trueprint (
notFalse) # True# 6.空值 if
(
None ==0 ) :print(
"None == 0")else:
print(
"None != 0")# C中NULL等于0 C++中nullptr也等于0# 7.Python中的所有变量本质上都是指针 =
[
a "a" ]=# 令b指向a指向的变量
b [ a 0
a]="b" print (
)# ['b']b= "a"
a = =
b "b" a
a # a会指向一个新的变量 print (
)# ab# 8.地板除 print
(
10//3 ) # 3# 9.Python中的整型可以按照长度动态分配内存 因此理论上没有大小限制 print
(
10**10000+1 ) # 100···001#!/usr/bin/env python3 # -*- coding: utf-8 -*-
二、字符串和编码
# 1.字符转换
print
(
ord("\n"))# 10print (
ord("风"))# 39118print (
"\u98ce")# 风 39118D与98ceH相等 \u表示采用Unicode编码# 2.字符串的编码 print
(
"北京市".("utf-8"encode))# b'\xe5\x8c\x97\xe4\xba\xac\xe5\xb8\x82' bytesprint (
b"\xe5\x8c\x97\xe4\xba\xac\xe5\xb8\x82".("utf-8"decode))# 北京市 strprint (
len("北京市"))# 3 统计字符数print (
len("北京市".("utf-8"encode)))# 9 统计字节数# 3.格式化字符串 print
(
"%dD %f %s %xH"%( 17 ,1.1, "A", 0x11) )# 17D 1.100000 A 11Hprint (
"|%-7.3f|"%( 12.34 ))# |12.340 | 总共7位 小数点后3位 左对齐list() =
三、数据结构
1.list
list可以由方括号或者[函数初始化:
legends "Qiyana" ,"Vi", "Thresh", "Jinx", "Zed"] print(
)# ['Qiyana', 'Vi', 'Thresh', 'Jinx', 'Zed']legends= list
li ( range(3))print(
)# [0, 1, 2]liprint (
list的正向索引和反向索引:
[0legends])# Qiyanaprint (
[1legends])# Viprint (
[-legends1])# Zedprint (
[-legends2])# Jinx. (
对list中的数据进行增删改查:
legends"Viktor"append)print(
)# ['Qiyana', 'Vi', 'Thresh', 'Jinx', 'Zed', 'Viktor']legends. (
legends1insert,"Ezreal") print(
)# ['Qiyana', 'Ezreal', 'Vi', 'Thresh', 'Jinx', 'Zed', 'Viktor']legends. (
legends)popprint(
)# ['Qiyana', 'Ezreal', 'Vi', 'Thresh', 'Jinx', 'Zed']legends. (
legends1pop)print(
)# ['Qiyana', 'Vi', 'Thresh', 'Jinx', 'Zed']legends. (
legends"Qiyana"remove)print(
)# ['Vi', 'Thresh', 'Jinx', 'Zed']legends[ -
legends2]="Pyke" print (
)# ['Vi', 'Thresh', 'Pyke', 'Zed']legendsprint (
"Thresh"in) # True legendsprint (
"Ezreal"notin ) # True legends= [
list中的数据类型也可以不同:
li "A" ,1, True, ]print legends(
)# ['A', 1, True, ['Qiyana', 'Vi', 'Thresh', 'Pyke', 'Zed']]liprint (
[-li1][-1])# Zedprint (
len())li# 4sort() =
[方法可以实现对list的原地排序:
li 2 ,4, 6, 5, 3, 1] .(
li)sortprint(
)# [1, 2, 3, 4, 5, 6]li. (
li=sortTruereverse)# 逆序排序print (
)# [6, 5, 4, 3, 2, 1]li= [
li "C" ,"C++", "Python"] .(
li=sortlenkey)# 按长排序print (
)# ['C', 'C++', 'Python']lienumerate() =
通过[函数可以在遍历时跟踪当前序号:
li "C" ,"C++", "Python"] for,
in keyenumerate value ( ):liprint(
,)key# 0 C value# 1 C++
# 2 Python
=
(
2.tuple
tuple本身是一个长度固定、元素不可变的list:
tup "Jinx" ,"Vi", "Shen") # 括号也可省略print (
)# ('Jinx', 'Vi', 'Shen')tupprint (
[0tup])# Jinx= tuple
tup ( [1,2, 3] )print(
)# (1, 2, 3)tup= tuple
tup ( "string")print(
)# ('s', 't', 'r', 'i', 'n', 'g')tup= (
对于含有单个元素的tuple要通过逗号来消除歧义:
tup 1 )print(
type())tup=( #
tup 1 ,)print(
type())tup元素的指向不变= #
元素不变指的是(而不是指向的内容不变:
tup "Jinx" ,["Vi" ,"Shen"] )[-
tup1][-1]="Miss Fortune" print (
)# 'Jinx', ['Vi', 'Miss Fortune'])tup= (
对元组进行运算:
tup 1 ,True, "str") +( False ,"Jinx") print(
)# (1, True, 'str', False, 'Jinx')tup= (
tup 1 ,True, "str") *3 print (
)# (1, True, 'str', 1, True, 'str', 1, True, 'str')tup, ,
如果你想将元组赋值给类似元组的变量,Python会将元组进行拆分:
a( b, )c= d( 1 ,2, (3 ,4) )print(
,,a, b) c# 1 2 3 4 d, =
利用这个特性可以方便地实现两个变量的交换:
a, b print b( a
,)a# 2 1 bfor ,
变量拆分也可以用来迭代元组或列表序列:
, iin j( k ( 1,2, 3) ,(4 ,5, 6) ,(7 ,8, 9) ):print(
,,i) j# 1 2 3 k# 4 5 6
# 7 8 9
count()
=
(方法可以用来统计元组中某个值的出现频率:
tup 1 ,0, 0, 8, 6) print(
.(tup0count))# 2enumerate() =
[函数可以用于在迭代时追踪元素下标:
li "Ezreal" ,"Neeko", "Thresh"] for,
in keyenumerate value ( ):liprint(
,)key# 0 Ezreal value# 1 Neeko
# 2 Thresh
=
"C"
3.dict
dict的初始化:
dic : {1, "C++": 3, "Python": 6} print(
)# {'C': 1, 'C++': 3, 'Python': 6}dic[ "C#"
对dict中的数据进行增删改查
dic]=2 print (
)# {'C': 1, 'C++': 3, 'Python': 6, 'C#': 2}dic. (
dic"C++"pop)# dict的pop方法必须传入参数print (
)# {'C': 1, 'Python': 6, 'C#': 2}dicdel [
"Python" dic]print(
)# {'C': 1, 'C#': 2}dic[ "C"
dic]=- 1 print(
)# {'C': -1, 'C#': 2}dicprint (
["C#"dic])# 2print (
.(dic"C"get))# -1print (
.(dic"Java"get))# Noneprint (
"C"in) # True dicprint (
"Java"in) # False dicprint (
获取字典全部的键和值:
.(dic)keys)# dict_keys(['C', 'C#'])print (
.(dic)values)# dict_values([-1, 2])= set
4.set
set的初始化:
s ( [1,2, 3, 2, 3] )# 重复元素在set中会被自动过滤print (
)# {1, 2, 3}s. (
set的添加和删除:
s4add)print(
)# {1, 2, 3, 4}s. (
s4remove)print(
)# {1, 2, 3}s= set
对set进行集合 *** 作:
s1 ( [1,2, 3] )=set
s2 ( [2,3, 4] )print(
&)s1 # {2, 3} s2print (
.(s1)intersection)s2# {2, 3}print (
|)s1 # {1, 2, 3, 4} s2print (
.(s1)union)s2# {1, 2, 3, 4}= [
四、切片
对list使用切片 *** 作符:
names "Sona" ,"Ezreal", "Vi", "Irelia", "Akali"] print(
[1names:3])# ['Ezreal', 'Vi'] 左闭右开区间print (
[:names3])# ['Sona', 'Ezreal', 'Vi'] 从0开始时0可以省略print (
[1names:])# ['Ezreal', 'Vi', 'Irelia', 'Akali'] 到最后一个截止最后一个也可省略print (
[-names3:-1])# ['Vi', 'Irelia'] 反向切片print (
[0names:5:2])# ['Sona', 'Vi', 'Akali'] 改变切片步长print (
对tuple和字符串使用切片 *** 作符:
(0,1, 2, 3, 4) [1:4])# (1, 2, 3)print (
"01234"[1:4])# 123# 1.Python简单循环分支 for
五、循环分支
in
range i ( 5):if< # <<=>>
2 i : print(
"<",="" end)elif==
2 i : print(
"=",="" end)else:
print(
,=">""" end)print(
)# 2.Python中的for-else结构for
in
range i ( 5):pass# 空语句
# break else
:
print(
"The break statement has been executed.")# 当for循环正常执行完毕时else中的语句就会被执行print (
六、函数
类型转换函数:
int("5"))# 5print (
int(5.5))# 5print (
float("5.5"))# 5.5print (
float(5))# 5.0print (
str(5))# 5print (
str(5.5))# 5.5print (
bool(""))# Falseprint (
bool(1))# Truedef calculate
Python可以以tuple的形式令一个函数返回多值:
( ,)a: breturn+
, a - b, a = b
addition( subtraction 1 calculate,2) print(
,)addition# 3 -1 subtractionprint (
(1calculate,2) )# (3, -1)关键字参数通常用于指定默认值或可选参数 关键字参数必须位于位置参数(如果有的话)之后
函数可以有一些位置参数(positional)和一些关键字参数(keyword)。def而且sum_:
( ,=a1 b ) :# 位置参数在前 关键字参数在后return +
print a ( b
(1sum_))# 2print (
(1sum_,2) )# 3def add_end
默认参数必须指向不可变对象:
( =[l]):.(
l"END"append)returnprint
( l
()add_end)# ['END']print (
()add_end)# ['END', 'END']def add_end
( =Nonel):ifis
None l : =[
l ] .(
l"END"append)returnprint
( l
()add_end)# ['END']print (
()add_end)# ['END']def get_sum
可变参数:
( *):nums=0
total for in
: i += numsreturn
total print i
( total
(1get_sum,2, 3) )# 6print (
(*get_sum[1,2, 3] ))# 6 通过*可以将list或者tuple中的元素作为可变参数传入def person
关键字参数:
( ,,name** age) :kwprint(
,,name) age( kw"Ezreal"
person,20) # Ezreal 20 {}( "Ezreal"
person,20, ="ADC" job,="Piltover" city)# Ezreal 20 {'job': 'ADC', 'city': 'Piltover'}def person_
( ,,name* age, ,) job: city# 命名关键字参数print (
,,name, age) job( city"Ezreal"
person_,20, ="ADC" job,="Piltover" city)# Ezreal 20 ADC Piltoverdef hanoi
利用递归函数解决汉诺塔问题:
( ,,n, a) b: cif==
1 n : print(
,,a, "->"= c"" sep)else:
(-
hanoi1n , ,, a) cprint b(
,,a, "->"= c"" sep)(-
hanoi1n , ,, b) a( c3
hanoi,"a", "b", "c") # 1.对dict进行迭代dict # a->c a->b c->b a->c b->a b->c a->c
七、迭代
=
"C" : {1, "C++": 3, "Python": 6} forin
dict i : print(
)# C C++ Pythonifor in
dict i . ()values:print(
)# 1 3 6ifor in
dict i . ()items:print(
)# ('C', 1) ('C++', 3) ('Python', 6)ifor ,
in idict j . ()items:print(
,)i# C 1 C++ 3 Python 6 j# 2.判断一个类型是否可迭代 from
.
import collectionsprintabc ( Iterable
isinstance("string",)) Iterable# Trueprint (
isinstance([(1,2) ,(3 ,4) ,(5 ,6) ],)) Iterable# Trueprint (
isinstance(2022,)) Iterable# False# 1.使用列表生成式创建列表 =
八、列表生成式
list
L ( *forx in x range x ( 5))print(
)# [0, 1, 4, 9, 16]L= list
L ( forinx range x ( 1,6) if% 2 x == 0 ) print(
)# [2, 4]L= list
L ( if%x 2 x == 0 else 0 for in range x ( 1,6) )print(
)# [0, 2, 0, 4, 0]L# 2.使用列表生成式获取当前目录下的文件和目录名 import
=
list os
L ( forini . i ( os"."listdir))print(
)# ['.DS_Store', 'venv', 'demo.html', 'main.py', '.idea']Lyield next()
九、生成器
一个带有yield的函数就是一个generator,它和普通函数不同,生成一个generator的过程看起来像是函数调用,但不会执行任何函数代码,直到对其调用yield才开始执行(在 for 循环中会自动调用)。虽然执行流程仍按函数的流程执行,但每执行到一个yield语句就会中断并返回一个迭代值,下次执行时从yield的下一个语句继续执行。
这看起来就好像一个函数在正常执行的过程中被# 1.使用generator生成斐波那契数列中断了数次,每次中断都会通过def返回当前的迭代值。
fib
( max):,,
n= a0 b , 0, 1while <
max n : yield,
= b
a, b + b= a + b
n 1 n for in
( i 5 fib):print(
)# 1 1 2 3 5i# 2.使用generator生成杨辉三角 def
triangles
( ):=[
ans ] =0
n while True
: =[
line ] forin
range i ( +1n ) :if==
0 i or == : i . n(
line1append)else:
.(
line[append-ans1n ] [-1i ] +[ - ans1n ] [])iyield=
+ line
n 1 n . (
ans)append=line0
n for in
( i ) triangles:print(
)=i+
n 1 n if ==
10 n : break# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# [1, 7, 21, 35, 35, 21, 7, 1]
# [1, 8, 28, 56, 70, 56, 28, 8, 1]
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
# 1.普通高阶函数
def
十、高阶函数
abs_sum
( ,,x) y: fun# 类似于函数指针return (
) fun+x( ) funprinty(
(-abs_sum1,1, abs) )# 2# 2.通过map求列表中所有元素的平方 def
square
( ):xreturn*
print x ( x
list(map(,[square0 ,1, 2] )))# [0, 1, 4] map将传入的函数依次作用到序列的每个元素# 3.通过reduce将列表转化为整数 from
import
reduce functools def add
( ,)x: yreturn*
10 x + print ( y
reduce(,[add1 ,2, 3] ))# 123 reduce把结果继续和序列的下一个元素做累积计算# 4.通过filter过滤出列表中的所有奇数 def
is_odd
( ):xreturn%
2 x == 1 print (
list(filter(,[is_odd1 ,2, 3, 4, 5] )))# [1, 3, 5] filter把传入的函数依次作用于每个元素后根据返回值是True还是False决定保留还是丢弃该元素# 5.通过sorted对列表按绝对值进行逆向排序 print
(
sorted([1,-2 ,3, -4 ,5] ,=abs key,=True reverse))# [5, -4, 3, -2, 1]# 1.通过匿名函数筛选奇数 print
十一、匿名函数
(
list(filter(lambda:% n2 n == 1 , range( 1,10) )))# 1.Python简单面向对象class
十二、面向对象编程
Legend
( object):def__init__
( ,,self) name: camp.=
self# 通过两个下划线将变量变为私有变量__name . name =
selfdef__camp __str__ camp
( ):selfreturn"%s: %s"
% ( . ,self.__name) self=__camp(
Ezreal "Ezreal" Legend,"Piltover") print(
)# Ezreal: PiltoverEzrealclass MID
( ):Legend# MID继承自Legendpass =
(
Zoe "Zoe" MID,"MountTargon") print(
)# Zoe: MountTargonZoeprint (
type())Ezrealprint( #
type())Zoeprint( #
isinstance(,)Zoe) Legend# Trueprint (
isinstance(,)Zoe) MID# True# 2.通过类属性和实例属性统计实例数 class
Brand
( object):=0
count def __init__
( ,)self: name.=
self.__name = name
Brand.count + Brand1count = (
Uni "Uni" Brand)=(
Sakura "Sakura" Brand)=(
Pilot "Pilot" Brand)print(
.)Brand# 3count# 3.通过类实现斐波那契数列 class
Fib
( object):def__init__
( ,)self: n.,
self.__a= self0__b , 1. =
selfdef__n __iter__ n
( ):selfreturndef
__next__ self
( ):self.,
self.__a= self.__b , self.__b+ self.__a if self.__b
. self:__a > selfraise__nreturn
. StopIteration
for selfin__a
( i 10 Fib):print(
)# 1 1 2 3 5 8i# 4.枚举类 from
import
= enum ( Enum
Month 'Month' Enum,('Jan' ,'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec') )print(
..Month)Jan# 1valueprint (
..Month)Nov# 11value# 文件打开 try
十三、文件 *** 作
:
=open
my_file ( "./main.py","r") exceptas
: FileNotFoundError print e(
"FileNotFoundError:",)finally e:
pass# 文件读写
try
:
print(
.(my_file)read).(
my_file"#"write)exceptas
: IOError print e(
"IOError:",)finally e:
pass# 文件关闭
.
(
my_file)closeimport# 1.获取 *** 作系统信息
十四、os模块
print os
(
.)os# posixnameprint (
.(os)uname)# posix.uname_result(sysname='Darwin', nodename='AtreusdeMBP', release='21.4.0', version='Darwin Kernel Version 21.4.0: Fri Mar 18 00:46:32 PDT 2022; root:xnu-8020.101.4~15/RELEASE_ARM64_T6000', machine='arm64')# 2. *** 作文件和目录 print
(
..os(path"."abspath))# /Users/atreus/PycharmProjects/pythonProjectprint (
..os(path"./"join,"test_dir") )# ./test_dir. (
os"./test_dir"mkdir)# 创建目录. (
os"./test_dir"rmdir)# 删除目录import # 1.使用json对dict进行序列化
十五、json模块
= json
"C"
languages : {1, "C++": 3, "Python": 6} print(
.(json)dumps)languages# {"C": 1, "C++": 3, "Python": 6}# 2.使用json对list进行序列化 =
[
legends "Ezreal" ,"Vi", "Jinx"] print(
.(json)dumps)legends# ["Ezreal", "Vi", "Jinx"]# 3.使用json进行反序列化 =
'{"C": 1, "C++": 3, "Python": 6}'
json_str = .
languages_dict ( json)loadsprintjson_str(
["C++"languages_dict])# 3# 4.使用json对对象进行序列化和反序列化 class
Legend
( object):def__init__
( ,,self) name: camp.=
self.name = name
selfdefcamp to_dict camp
( ):legendreturn"name"
: {
., legend"camp"name:
.} legend=camp
(
Ezreal "Ezreal" Legend,"Piltover") print(
.(json,dumps=Ezreal) default)to_dict# {"name": "Ezreal", "camp": "Piltover"}def to_legend
( ):json_dictreturn(
[ Legend"name"json_dict],["camp" json_dict])print(
.(json'{"name": "Jinx", "camp": "Zaun"}'loads,=) object_hook)to_legendimport# 1.match # <__main__.Legend object at 0x104def100>
十六、正则表达式
print re
(
.matchre(r"^\d{3}\-\d{3,8}$","010-10010") )print( #
.matchre(r"^\d{3}\-\d{3,8}$","010 10010") )# None= .
ans match re(r"^(\d{3})\-(\d{3,8})$","010-10010") print(
.(ans0group))# 010-10010print (
.(ans1group))# 010print (
.(ans2group))# 10010print (
.matchre(r"^(\d+)(0*)$","12300") .()groups)# ('12300', '') 贪婪匹配print (
.matchre(r"^(\d+?)(0*)$","12300") .()groups)# ('123', '00') 非贪婪匹配# 2.split print
(
.(rer"\s+"split,"a b c d e") )# ['a', 'b', 'c', 'd', 'e']# 1.datetime from
十七、datetime
import
print datetime ( datetime
.(datetime)now)# 2022-05-10 10:16:41.384150print (
(2021datetime,12, 25, 8, 0) )# 2021-12-25 08:00:00print (
(1970datetime,1, 1, 8, 0) .()timestamp)# 0.0print (
.(datetime0.0fromtimestamp))# 1970-01-01 08:00:00print (
.(datetime)now.("%a, %b %d, %H:%M"strftime))# Tue, May 10, 10:24# 1.namedtuple from
十八、collections
import
= collections ( namedtuple
Point "Point" namedtuple,["x" ,"y"] )# 将元组定义为一个坐标= (
point 1 Point,0) print(
.,point.x) point# 1 0y= (
Circle "Circle" namedtuple,["x" ,"y", "r"] )# 将元组定义为一个圆= (
circle 0 Circle,0, 1) print(
)# Circle(x=0, y=0, r=1)circle# 2.deque from
import
= collections ( deque
L [ deque1,2, 3, 4, 5] )# 双向链表print (
)# deque([1, 2, 3, 4, 5])L. (
L6append)print(
)# deque([1, 2, 3, 4, 5, 6])L. (
L0appendleft)print(
)# deque([0, 1, 2, 3, 4, 5, 6])L. (
L)popprint(
)# deque([0, 1, 2, 3, 4, 5])L. (
L)popleftprint(
)# deque([1, 2, 3, 4, 5])L# 3.OrderedDict from
import
= collections ( OrderedDict
order_dict [ OrderedDict("C",1) ,("C++" ,3) ,("Python" ,6) ])# OrderedDict的Key会按照插入的顺序而不是Key本身排序print (
)# OrderedDict([('C', 1), ('C++', 3), ('Python', 6)])order_dictprint (
list(.(order_dict)keys))# ['C', 'C++', 'Python']# 4.Counter from
import
= collections ( Counter
counter ) Counterforin
"Ezreal" i : # 通过循环更新计数器[ ]
counter+=i1 print (
)# Counter({'E': 1, 'z': 1, 'r': 1, 'e': 1, 'a': 1, 'l': 1})counter. (
counter"EZ"update)# 一次性更新计数器print (
)# Counter({'E': 2, 'z': 1, 'r': 1, 'e': 1, 'a': 1, 'l': 1, 'Z': 1})counter# 1.利用pillow生成验证码 from
十九、pillow
import
, PIL , Image, ImageDrawimport ImageFont# 随机字母 ImageFilter
def random
rand_char
( ):returnchr
( .(random65randint,90) )# 随机颜色def
rand_color
( ):return.
( random64randint,255) ,.( random64randint,255) ,.( random64randint,255) defback_rand_color
( ):return.
( random32randint,127) ,.( random32randint,127) ,.( random32randint,127) # 创建Image对象=
60
width * 4 = 60
height = .
image ( Image"RGB"new,(, )width, height(255 ,255, 255) )# 创建Font对象=
.
font ( ImageFont"Arial.ttf"truetype,36) # 创建Draw对象=
.
draw ( ImageDraw)Draw# 填充每个像素imagefor
in
range x ( ):widthforin
range y ( ):height.(
draw(point,)x, y=( fill)rand_color)# 输出文字for
in
range t ( 4):.(
draw(text60*+ 10 t , 10) ,() rand_char,=, font=font( fill)back_rand_color)# 保存图片.
(
image"./code.jpg"save,"jpeg") # 1.通过requests访问网页import
二十、requests
=
. requests
r ( requests"https://www.liaoxuefeng.com/"get)print(
.)r# 200status_codeprint (
.[r0text:15] ) #
二十一、运算符
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)