Skip to content

Latest commit

History

History
1253 lines (980 loc) · 18.8 KB

File metadata and controls

1253 lines (980 loc) · 18.8 KB

Python 3 备忘清单

Python 备忘单是 Python 3 编程语言的单页参考表

入门

介绍

Hello World

>>>print("Hello, World!")
Hello, World!

Python 中著名的“Hello World”程序

变量

age=18# 年龄是 int 类型name="John"# name 现在是 str 类型print(name)

Python 不能在没有赋值的情况下声明变量

数据类型

:-:-
strText
int, float, complexNumeric
list, tuple, rangeSequence
dictMapping
set, frozensetSet
boolBoolean
bytes, bytearray, memoryviewBinary

查看: Data Types

Slicing String

>>>msg="Hello, World!">>>print(msg[2:5])
llo

查看: Strings

Lists

mylist= []
mylist.append(1)
mylist.append(2)
foriteminmylist:
print(item) # 打印输出 1,2

查看: Lists

If Else

num=200ifnum>0:
print("num is greater than 0")
else:
print("num is not greater than 0")

查看: 流程控制

循环

foriteminrange(6):
ifitem==3: breakprint(item)
else:
print("Finally finished!")

查看: Loops

函数

>>>defmy_function():
... print("来自函数的你好")
...
>>>my_function()
来自函数的你好

查看: Functions

文件处理

withopen("myfile.txt", "r", encoding='utf8') asfile:
forlineinfile:
print(line)

查看: 文件处理

算术

result=10+30# => 40result=40-10# => 30result=50*5# => 250result=16/4# => 4.0 (Float Division)result=16//4# => 4 (Integer Division)result=25%2# => 1result=5**3# => 125

/ 表示 x 和 y 的商,// 表示 x 和 y 的底商,另见 StackOverflow

加等于

counter=0counter+=10# => 10counter=0counter=counter+10# => 10message="Part 1."# => Part 1.Part 2.message+="Part 2."

f-字符串(Python 3.6+)

>>>website='Quick Reference'>>>f"Hello, {website}""Hello, Quick Reference">>>num=10>>>f'{num} + 10 = {num+10}''10 + 10 = 20'

查看: [Python F-Strings](#f-字符串(Python 3.6+))

Python 数据类型

字符串

hello="Hello World"hello='Hello World'multi_string="""Multiline StringsLorem ipsum dolor sit amet,consectetur adipiscing elit """

查看: Strings

数字

x=1# inty=2.8# floatz=1j# complex>>>print(type(x))
<class'int'>

布尔值

my_bool=Truemy_bool=Falsebool(0) # => Falsebool(1) # => True

Lists

list1= ["apple", "banana", "cherry"]
list2= [True, False, False]
list3= [1, 5, 7, 9, 3]
list4=list((1, 5, 7, 9, 3))

查看: Lists

元组 Tuple

my_tuple= (1, 2, 3)
my_tuple=tuple((1, 2, 3))

类似于 List 但不可变

Set

set1= {"a", "b", "c"} set2=set(("a", "b", "c"))

一组独特的项目/对象

字典 Dictionary

>>>empty_dict= {}
>>>a= {"one": 1, "two": 2, "three": 3}
>>>a["one"]
1>>>a.keys()
dict_keys(['one', 'two', 'three'])
>>>a.values()
dict_values([1, 2, 3])
>>>a.update({"four": 4})
>>>a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>>a['four']
4

Key:值对,JSON 类对象

Casting

整数 Integers

x=int(1) # x 将是 1y=int(2.8) # y 将是 2z=int("3") # z 将是 3

浮点数 Floats

x=float(1) # x 将为 1.0y=float(2.8) # y 将是 2.8z=float("3") # z 将为 3.0w=float("4.2") # w 将是 4.2

字符串 Strings

x=str("s1") # x 将是 's1'y=str(2) # y 将是 '2'z=str(3.0) # z 将是 '3.0'

Python 字符串

类数组

>>>hello="Hello, World">>>print(hello[1])
e>>>print(hello[-1])
d

获取位置 1 或最后的字符

循环

>>>forcharin"foo":
... print(char)
foo

遍历单词 foo 中的字母

切片字符串

 ┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
01234567
-7 -6 -5 -4 -3 -2 -1

>>>s='mybacon'>>>s[2:5]
'bac'>>>s[0:2]
'my'

>>>s='mybacon'>>>s[:2]
'my'>>>s[2:]
'bacon'>>>s[:2] +s[2:]
'mybacon'>>>s[:]
'mybacon'

>>>s='mybacon'>>>s[-5:-1]
'baco'>>>s[2:6]
'baco'

步长

>>>s='12345'*5>>>s'1234512345123451234512345'>>>s[::5]
'11111'>>>s[4::5]
'55555'>>>s[::-5]
'55555'>>>s[::-1]
'5432154321543215432154321'

字符串长度

>>>hello="Hello, World!">>>print(len(hello))
13

len() 函数返回字符串的长度

多份

>>>s='===+'>>>n=8>>>s*n'===+===+===+===+===+===+===+===+'

检查字符串

>>>s='spam'>>>sin'I saw spamalot!'True>>>snotin'I saw The Holy Grail!'True

连接

>>>s='spam'>>>t='egg'>>>s+t'spamegg'>>>'spam''egg''spamegg'

格式化

name="John"print("Hello, %s!"%name)

name="John"age=23print("%s is %d years old."% (name, age))

format() 方法

txt1="My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2="My name is {0}, I'm {1}".format("John", 36)
txt3="My name is {}, I'm {}".format("John", 36)

Input 输入

>>>name=input("Enter your name: ")
Enteryourname: Tom>>>name'Tom'

从控制台获取输入数据

Join 加入

>>>"#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'

Endswith 以..结束

>>>"Hello, world!".endswith("!")
True

转义符号

转义符号对应的操作
\\输出反斜杠
\'输出单引号
\"输出双引号
\n换行
\t水平制表符
\r光标回到首位
\b退格

Python F 字符串(自 Python 3.6+ 起)

f-Strings 用法

>>>website='Reference'>>>f"Hello, {website}""Hello, Reference">>>num=10>>>f'{num} + 10 = {num+10}''10 + 10 = 20'>>>f"""He said {"I'm John"}""""He said I'm John">>>f'5 {"{stars}"}''5 {stars}'>>>f'{{5}} {"stars"}''{5} stars'>>>name='Eric'>>>age=27>>>f"""Hello!... I'm {name}.... I'm {age}.""""Hello!\n I'm Eric.\n I'm 27."

它从 Python 3.6 开始可用,另见: 格式化的字符串文字

f-Strings 填充对齐

>>>f'{"text":10}'# [宽度]'text '>>>f'{"test":*>10}'# 向左填充'******test'>>>f'{"test":*<10}'# 填写正确'test******'>>>f'{"test":*^10}'# 填充中心'***test***'>>>f'{12345:0>10}'# 填写数字'0000012345'

f-Strings 类型

>>>f'{10:b}'# binary 二进制类型'1010'>>>f'{10:o}'# octal 八进制类型'12'>>>f'{200:x}'# hexadecimal 十六进制类型'c8'>>>f'{200:X}''C8'>>>f'{345600000000:e}'# 科学计数法'3.456000e+11'>>>f'{65:c}'# 字符类型'A'>>>f'{10:#b}'# [类型] 带符号(基础)'0b1010'>>>f'{10:#o}''0o12'>>>f'{10:#x}''0xa'

F-Strings Sign

>>>f'{12345:+}'# [sign] (+/-)'+12345'>>>f'{-12345:+}''-12345'>>>f'{-12345:+10}'' -12345'>>>f'{-12345:+010}''-000012345'

F-Strings 其它

>>>f'{-12345:0=10}'# 负数'-000012345'>>>f'{12345:010}'# [0] 快捷方式(不对齐)'0000012345'>>>f'{-12345:010}''-000012345'>>>importmath# [.precision]>>>math.pi3.141592653589793>>>f'{math.pi:.2f}''3.14'>>>f'{1000000:,.2f}'# [分组选项]'1,000,000.00'>>>f'{1000000:_.2f}''1_000_000.00'>>>f'{0.25:0%}'# 百分比'25.000000%'>>>f'{0.25:.0%}''25%'

Python Lists

定义

>>>li1= []
>>>li1
[]
>>>li2= [4, 5, 6]
>>>li2
[4, 5, 6]
>>>li3=list((1, 2, 3))
>>>li3
[1, 2, 3]
>>>li4=list(range(1, 11))
>>>li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

生成

>>>list(filter(lambdax : x%2==1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x**2forxinrange (1, 11) ifx%2==1]
[1, 9, 25, 49, 81]
>>> [xforxin [3, 4, 5, 6, 7] ifx>5]
[6, 7]
>>>list(filter(lambdax: x>5, [3, 4, 5, 6, 7]))
[6, 7]

添加

>>>li= []
>>>li.append(1)
>>>li
[1]
>>>li.append(2)
>>>li
[1, 2]
>>>li.append(4)
>>>li
[1, 2, 4]
>>>li.append(3)
>>>li
[1, 2, 4, 3]

List 切片

列表切片的语法:

a_list[start:end]
a_list[start:end:step]

切片

>>>a= ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[2:5]
['bacon', 'tomato', 'ham']
>>>a[-5:-2]
['egg', 'bacon', 'tomato']
>>>a[1:4]
['egg', 'bacon', 'tomato']

省略索引

>>>a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>>a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>>a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

迈着大步

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[0:6:2]
['spam', 'bacon', 'ham']
>>>a[1:6:2]
['egg', 'tomato', 'lobster']
>>>a[6:0:-2]
['lobster', 'tomato', 'egg']
>>>a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>>a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

删除

>>>li= ['bread', 'butter', 'milk']
>>>li.pop()
'milk'>>>li
['bread', 'butter']
>>>delli[0]
>>>li
['butter']

使用权

>>>li= ['a', 'b', 'c', 'd']
>>>li[0]
'a'>>>li[-1]
'd'>>>li[4]
Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>IndexError: listindexoutofrange

连接

>>>odd= [1, 3, 5]
>>>odd.extend([9, 11, 13])
>>>odd
[1, 3, 5, 9, 11, 13]
>>>odd= [1, 3, 5]
>>>odd+ [9, 11, 13]
[1, 3, 5, 9, 11, 13]

排序和反转

>>>li= [3, 1, 3, 2, 5]
>>>li.sort()
>>>li
[1, 2, 3, 3, 5]
>>>li.reverse()
>>>li
[5, 3, 3, 2, 1]

计数

>>>li= [3, 1, 3, 2, 5]
>>>li.count(3)
2

重复

>>>li= ["re"] *3>>>li
['re', 're', 're']

Python 流程控制

基本

num=5ifnum>10:
print("num is totally bigger than 10.")
elifnum<10:
print("num is smaller than 10.")
else:
print("num is indeed 10.")

一行

>>>a=330>>>b=200>>>r="a"ifa>belse"b">>>print(r)
a

else if

value=Trueifnotvalue:
print("Value is False")
elifvalueisNone:
print("Value is None")
else:
print("Value is True")

Python 循环

基础

primes= [2, 3, 5, 7]
forprimeinprimes:
print(prime)

有索引

animals= ["dog", "cat", "mouse"]
fori, valueinenumerate(animals):
print(i, value)

While

x=0whilex<4:
print(x)
x+=1# Shorthand for x = x + 1

Break

x=0forindexinrange(10):
x=index*10ifindex==5:
breakprint(x)

Continue

forindexinrange(3, 8): x=index*10ifindex==5:
continueprint(x)

范围

foriinrange(4):
print(i) # Prints: 0 1 2 3foriinrange(4, 8):
print(i) # Prints: 4 5 6 7foriinrange(4, 10, 2):
print(i) # Prints: 4 6 8

使用 zip()

name= ['Pete', 'John', 'Elizabeth']
age= [6, 23, 44]
forn, ainzip(name, age):
print('%s is %d years old'%(n, a))

列表理解

result= [x**2forxinrange(10) ifx%2==0]
print(result)
# [0, 4, 16, 36, 64]

Python 函数

基础

defhello_world(): print('Hello, World!')

返回

defadd(x, y):
print("x is %s, y is %s"%(x, y))
returnx+yadd(5, 6) # => 11

位置参数

defvarargs(*args):
returnargsvarargs(1, 2, 3) # => (1, 2, 3)

关键字参数

defkeyword_args(**kwargs):
returnkwargs# => {"big": "foot", "loch": "ness"}keyword_args(big="foot", loch="ness")

返回多个

defswap(x, y):
returny, xx=1y=2x, y=swap(x, y) # => x = 2, y = 1

默认值

defadd(x, y=10):
returnx+yadd(5) # => 15add(5, 20) # => 25

匿名函数

# => True
(lambdax: x>2)(3)
# => 5
(lambdax, y: x**2+y**2)(2, 1)

Python 模块

导入模块

importmathprint(math.sqrt(16)) # => 4.0

从一个模块导入

frommathimportceil, floorprint(ceil(3.7)) # => 4.0print(floor(3.7)) # => 3.0

全部导入

frommathimport*

缩短模块

importmathasm# => Truemath.sqrt(16) ==m.sqrt(16)

功能和属性

importmathdir(math)

Python 文件处理

读取文件

逐行

withopen("myfile.txt") asfile:
forlineinfile:
print(line)

带行号

file=open('myfile.txt', 'r')
fori, lineinenumerate(file, start=1):
print("Number %s: %s"% (i, line))

字符串

写一个字符串

contents= {"aa": 12, "bb": 21}
withopen("myfile1.txt", "w+") asfile:
file.write(str(contents))

读取一个字符串

withopen('myfile1.txt', "r+") asfile:
contents=file.read()
print(contents)

对象

写一个对象

contents= {"aa": 12, "bb": 21}
withopen("myfile2.txt", "w+") asfile:
file.write(json.dumps(contents))

读取对象

withopen('myfile2.txt', "r+") asfile:
contents=json.load(file)
print(contents)

删除文件

importosos.remove("myfile.txt")

检查和删除

importosifos.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")

删除文件夹

importosos.rmdir("myfolder")

Python 类和继承

Defining

classMyNewClass:
pass# Class Instantiationmy=MyNewClass()

构造函数

classAnimal:
def__init__(self, voice):
self.voice=voicecat=Animal('Meow')
print(cat.voice) # => Meowdog=Animal('Woof') print(dog.voice) # => Woof

方法

classDog:
# 类的方法defbark(self):
print("Ham-Ham")
charlie=Dog()
charlie.bark() # => "Ham-Ham"

类变量

classMyClass:
class_variable="A class variable!"# => 一个类变量!print(MyClass.class_variable)
x=MyClass()
# => 一个类变量!print(x.class_variable)

Super() 函数

classParentClass:
defprint_test(self):
print("Parent Method")
classChildClass(ParentClass):
defprint_test(self):
print("Child Method")
# 调用父级的 print_test()super().print_test() 

>>>child_instance=ChildClass()
>>>child_instance.print_test()
ChildMethodParentMethod

repr() 方法

classEmployee:
def__init__(self, name):
self.name=namedef__repr__(self):
returnself.namejohn=Employee('John')
print(john) # => John

用户定义的异常

classCustomError(Exception):
pass

多态性

classParentClass:
defprint_self(self):
print('A')
classChildClass(ParentClass):
defprint_self(self):
print('B')
obj_A=ParentClass()
obj_B=ChildClass()
obj_A.print_self() # => Aobj_B.print_self() # => B

覆盖

classParentClass:
defprint_self(self):
print("Parent")
classChildClass(ParentClass):
defprint_self(self):
print("Child")
child_instance=ChildClass()
child_instance.print_self() # => Child

继承

classAnimal: def__init__(self, name, legs):
self.name=nameself.legs=legsclassDog(Animal):
defsound(self):
print("Woof!")
Yoki=Dog("Yoki", 4)
print(Yoki.name) # => YOKIprint(Yoki.legs) # => 4Yoki.sound() # => Woof!

各种各样的

注释

# 这是单行注释

""" 可以写多行字符串 使用三个",并且经常使用 作为文档。"""

''' 可以写多行字符串 使用三个',并且经常使用 作为文档。'''

生成器

defdouble_numbers(iterable):
foriiniterable:
yieldi+i

生成器可帮助您编写惰性代码

要列出的生成器

values= (-xforxin [1,2,3,4,5])
gen_to_list=list(values)
# => [-1, -2, -3, -4, -5]print(gen_to_list)

处理异常

try:
# 使用“raise”来引发错误raiseIndexError("这是一个索引错误")
exceptIndexErrorase:
pass# pass只是一个空操作。 通常你会在这里做恢复。except (TypeError, NameError):
pass# 如果需要,可以一起处理多个异常。else: # try/except 块的可选子句。 必须遵循除块之外的所有内容print("All good!") # 仅当 try 中的代码未引发异常时运行finally: # 在所有情况下执行print("我们可以在这里清理资源")

另见