国产成人精品999视频&日本一区二区亚洲人妻精品&久久久精品国产99久久精&99热这里只有成人精品国产&精品国产剧情av一区二区&成人亚洲精品久久久久app&国产精品美女高潮抽搐A片

Python 3 備忘清單

Python 備忘單是 Python 3 編程語言的單頁參考表

入門

介紹

Hello World

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

Python 中著名的“Hello World”程序

變量

age = 18      # 年齡是 int 類型
name = "John" # name 現(xiàn)在是 str 類型
print(name)

Python 不能在沒有賦值的情況下聲明變量

數(shù)據(jù)類型

:-:-
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)
for item in mylist:
    print(item) # 打印輸出 1,2

查看: Lists

If Else

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

查看: 流程控制

循環(huán)

for item in range(6):
    if item == 3: break
    print(item)
else:
    print("Finally finished!")

查看: Loops

函數(shù)

>>> def my_function():
...     print("來自函數(shù)的你好")
...
>>> my_function()
來自函數(shù)的你好

查看: Functions

文件處理

with open("myfile.txt", "r", encoding='utf8') as file:
    for line in file:
        print(line)

查看: 文件處理

算術(shù)

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

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

加等于

counter = 0
counter += 10           # => 10
counter = 0
counter = counter + 10  # => 10
message = "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 數(shù)據(jù)類型

字符串

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

查看: Strings

數(shù)字

x = 1    # int
y = 2.8  # float
z = 1j   # complex
>>> print(type(x))
<class 'int'>

布爾值

my_bool = True 
my_bool = False
bool(0)     # => False
bool(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"))

一組獨(dú)特的項(xiàng)目/對(duì)象

字典 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:值對(duì),JSON 類對(duì)象

Casting

整數(shù) Integers

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

浮點(diǎn)數(shù) Floats

x = float(1)     # x 將為 1.0
y = float(2.8)   # y 將是 2.8
z = float("3")   # z 將為 3.0
w = 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 字符串

類數(shù)組

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

獲取位置 1 或最后的字符

循環(huán)

>>> for char in "foo":
...     print(char)
f
o
o

遍歷單詞 foo 中的字母

切片字符串

 ┌───┬───┬───┬───┬───┬───┬───┐
 | m | y | b | a | c | o | n |
 └───┴───┴───┴───┴───┴───┴───┘
 0   1   2   3   4   5   6   7
-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'

步長(zhǎng)

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

字符串長(zhǎng)度

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

len() 函數(shù)返回字符串的長(zhǎng)度

多份

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

檢查字符串

>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s not in '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 = 23
print("%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: ")
Enter your name: Tom
>>> name
'Tom'

從控制臺(tái)獲取輸入數(shù)據(jù)

Join 加入

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

Endswith 以..結(jié)束

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

轉(zhuǎn)義符號(hào)

轉(zhuǎn)義符號(hào)對(duì)應(yīng)的操作
\\輸出反斜杠
\'輸出單引號(hào)
\"輸出雙引號(hào)
\n換行
\t水平制表符
\r光標(biāo)回到首位
\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 填充對(duì)齊

>>> f'{"text":10}'   # [寬度]
'text      '
>>> f'{"test":*>10}' # 向左填充
'******test'
>>> f'{"test":*<10}' # 填寫正確
'test******'
>>> f'{"test":*^10}' # 填充中心
'***test***'
>>> f'{12345:0>10}'  # 填寫數(shù)字
'0000012345'

f-Strings 類型

>>> f'{10:b}'     # binary 二進(jìn)制類型
'1010'
>>> f'{10:o}'     # octal 八進(jìn)制類型
'12'
>>> f'{200:x}'    # hexadecimal 十六進(jìn)制類型
'c8'
>>> f'{200:X}'
'C8'
>>> f'{345600000000:e}' # 科學(xué)計(jì)數(shù)法
'3.456000e+11'
>>> f'{65:c}'       # 字符類型
'A'
>>> f'{10:#b}'      # [類型] 帶符號(hào)(基礎(chǔ))
'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}'  # 負(fù)數(shù)
'-000012345'
>>> f'{12345:010}'    # [0] 快捷方式(不對(duì)齊)
'0000012345'
>>> f'{-12345:010}'
'-000012345'
>>> import math       # [.precision]
>>> math.pi
3.141592653589793
>>> f'{math.pi:.2f}'
'3.14'
>>> f'{1000000:,.2f}' # [分組選項(xiàng)]
'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(lambda x : x % 2 == 1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x ** 2 for x in range (1, 11) if  x % 2 == 1]
[1, 9, 25, 49, 81]
>>> [x for x in [3, 4, 5, 6, 7] if x > 5]
[6, 7]
>>> list(filter(lambda x: 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']
>>> del li[0]
>>> li
['butter']

使用權(quán)

>>> li = ['a', 'b', 'c', 'd']
>>> li[0]
'a'
>>> li[-1]
'd'
>>> li[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

連接

>>> 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]

排序和反轉(zhuǎn)

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

計(jì)數(shù)

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

重復(fù)

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

Python 流程控制

基本

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

一行

>>> a = 330
>>> b = 200
>>> r = "a" if a > b else "b"
>>> print(r)
a

else if

value = True
if not value:
    print("Value is False")
elif value is None:
    print("Value is None")
else:
    print("Value is True")

Python 循環(huán)

基礎(chǔ)

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

有索引

animals = ["dog", "cat", "mouse"]
for i, value in enumerate(animals):
    print(i, value)

While

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

Break

x = 0
for index in range(10):
    x = index * 10
    if index == 5:
        break
    print(x)

Continue

for index in range(3, 8): 
    x = index * 10
    if index == 5:
        continue
    print(x)

范圍

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

使用 zip()

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

列表理解

result = [x**2 for x in range(10) if x % 2 == 0]
 
print(result)
# [0, 4, 16, 36, 64]

Python 函數(shù)

基礎(chǔ)

def hello_world():  
    print('Hello, World!')

返回

def add(x, y):
    print("x is %s, y is %s" %(x, y))
    return x + y
add(5, 6)    # => 11

位置參數(shù)

def varargs(*args):
    return args
varargs(1, 2, 3)  # => (1, 2, 3)

關(guān)鍵字參數(shù)

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

返回多個(gè)

def swap(x, y):
    return y, x
x = 1
y = 2
x, y = swap(x, y)  # => x = 2, y = 1

默認(rèn)值

def add(x, y=10):
    return x + y
add(5)      # => 15
add(5, 20)  # => 25

匿名函數(shù)

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

Python 模塊

導(dǎo)入模塊

import math
print(math.sqrt(16))  # => 4.0

從一個(gè)模塊導(dǎo)入

from math import ceil, floor
print(ceil(3.7))   # => 4.0
print(floor(3.7))  # => 3.0

全部導(dǎo)入

from math import *

縮短模塊

import math as m
# => True
math.sqrt(16) == m.sqrt(16)

功能和屬性

import math
dir(math)

Python 文件處理

讀取文件

逐行

with open("myfile.txt") as file:
    for line in file:
        print(line)

帶行號(hào)

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

字符串

寫一個(gè)字符串

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

讀取一個(gè)字符串

with open('myfile1.txt', "r+") as file:
    contents = file.read()
print(contents)

對(duì)象

寫一個(gè)對(duì)象

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

讀取對(duì)象

with open('myfile2.txt', "r+") as file:
    contents = json.load(file)
print(contents)

刪除文件

import os
os.remove("myfile.txt")

檢查和刪除

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

刪除文件夾

import os
os.rmdir("myfolder")

Python 類和繼承

Defining

class MyNewClass:
    pass
# Class Instantiation
my = MyNewClass()

構(gòu)造函數(shù)

class Animal:
    def __init__(self, voice):
        self.voice = voice
 
cat = Animal('Meow')
print(cat.voice)    # => Meow
 
dog = Animal('Woof') 
print(dog.voice)    # => Woof

方法

class Dog:
    # 類的方法
    def bark(self):
        print("Ham-Ham")
 
charlie = Dog()
charlie.bark()   # => "Ham-Ham"

類變量

class MyClass:
    class_variable = "A class variable!"
# => 一個(gè)類變量!
print(MyClass.class_variable)
x = MyClass()
 
# => 一個(gè)類變量!
print(x.class_variable)

Super() 函數(shù)

class ParentClass:
    def print_test(self):
        print("Parent Method")
 
class ChildClass(ParentClass):
    def print_test(self):
        print("Child Method")
        # 調(diào)用父級(jí)的 print_test()
        super().print_test() 

>>> child_instance = ChildClass()
>>> child_instance.print_test()
Child Method
Parent Method

repr() 方法

class Employee:
    def __init__(self, name):
        self.name = name
 
    def __repr__(self):
        return self.name
 
john = Employee('John')
print(john)  # => John

用戶定義的異常

class CustomError(Exception):
    pass

多態(tài)性

class ParentClass:
    def print_self(self):
        print('A')
 
class ChildClass(ParentClass):
    def print_self(self):
        print('B')
 
obj_A = ParentClass()
obj_B = ChildClass()
 
obj_A.print_self() # => A
obj_B.print_self() # => B

覆蓋

class ParentClass:
    def print_self(self):
        print("Parent")
 
class ChildClass(ParentClass):
    def print_self(self):
        print("Child")
 
child_instance = ChildClass()
child_instance.print_self() # => Child

繼承

class Animal: 
    def __init__(self, name, legs):
        self.name = name
        self.legs = legs
        
class Dog(Animal):
    def sound(self):
        print("Woof!")
 
Yoki = Dog("Yoki", 4)
print(Yoki.name) # => YOKI
print(Yoki.legs) # => 4
Yoki.sound()     # => Woof!

各種各樣的

注釋

# 這是單行注釋

""" 可以寫多行字符串
    使用三個(gè)",并且經(jīng)常使用
    作為文檔。
"""

''' 可以寫多行字符串
    使用三個(gè)',并且經(jīng)常使用
    作為文檔。
'''

生成器

def double_numbers(iterable):
    for i in iterable:
        yield i + i

生成器可幫助您編寫惰性代碼

要列出的生成器

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

處理異常

try:
    # 使用“raise”來引發(fā)錯(cuò)誤
    raise IndexError("這是一個(gè)索引錯(cuò)誤")
except IndexError as e:
    pass                 # pass只是一個(gè)空操作。 通常你會(huì)在這里做恢復(fù)。
except (TypeError, NameError):
    pass                 # 如果需要,可以一起處理多個(gè)異常。
else:                    # try/except 塊的可選子句。 必須遵循除塊之外的所有內(nèi)容
    print("All good!")   # 僅當(dāng) try 中的代碼未引發(fā)異常時(shí)運(yùn)行
finally:                 # 在所有情況下執(zhí)行
    print("我們可以在這里清理資源")

另見