Python 学习笔记
Comment
#
单行注释""" comment """
多行注释
# This is comment
"""
This also is also comment
"""
Date type
五种标准数据类型:
- Numbers
- String
- List
- Tuple
- Dictionary
需要注意的是 Python 中字符串和列表中下标的使用方式:
- start to end: 下标从 0 开始递增
- end to start: 下标从 -1 开始递减
Number, String
# number, string
integer, float_num = 1, 1.1
# <class 'int'> <class 'float'> <class 'str'>
print(type(integer), type(float_num), type(string))
String
string = "1.1"
# 1 2 1.
print(string[0], string[-1], string[:-1])
List
List 常用操作:
- 初始化:
[1, 2, 3]
[element] * n
: 创建一个 List,其中有 n 个元素,每个元素都是 element
- 插入:
list.append(element)
: 在末尾插入list.insert(index, element)
: 在指定位置插入元素list.extend(list2)
: 插入另一个列表
- 删除:
del list[index]
: 删除 index 位置的元素list.pop([index=-1])
: 删除指定位置的元素,默认为 -1list.remove(element)
: 删除第一个匹配的元素
- 访问:
list[index] = element
list.index(element)
list[start:end]
- 常用操作
list1 + list2
: 拼接两个 Listlen(list)
: 列表长度max(list)
/min(list)
: 返回列表中最大或最小元素list.sort(key=None, reverse=false)
: 排序element in list
# List
fruit_list = ["Apple", "Banana"]
print(fruit_list[0], fruit_list[-1]) # Apple Pear
del fruit_list[2]
print(fruit_list + ["Peach"])
fruit_list2 = ["Apple", "Banana"]
fruit_list.extend(fruit_list2)
for fruit in fruit_list:
print(fruit)
Tuple
Tuple 元素不能修改
Tuple 常用操作:
- 创建:
tup = (1, '2', "123")
- 访问:
tup[index]
,tup[1:2]
- 拼接:
tup3 = tup1 + tup2
- 删除:
del tup
- 常用操作:
len(tup)
element in tup
max(tup)
/min(tup)
: 返回 tuple 中最大或最小元素tuple(list)
: 将列表转化为 tuple
# Tuple
# data in tuple can not be modified
tup = ("key", "value", "seq")
print(tup[0], tup[1], tup[2], tup)
tup2 = tup + ("key1", "value1")
print(tup2, tup2[1:]) # ('key', 'value', 'seq', 'key1', 'value1')
del tup2
Dictionary
Dictionary 的 key 必须是不可变的
Dictionary 常用操作:
- 创建:
dic = {1: 1, 2: '2', "a" "123"}
, - 访问:
dic[key]
,dic.get(key, default=None)
- 删除:
del del dic[key]
- 常用操作:
len(dic)
key in dic
,dic.hasKey(key)
dic.copy()
: 浅拷贝dic.items
,dict.keys()
,dic.values()
# Dictionary
# key must be immutable, so can not be list
dic = {"key1": "value1", "key2": "value2", 3: 1}
dic[3] += 2
del dic["key2"]
print(dic["key1"], dic[3], type(dic), len(dic), str(dic))
dic2 = dic.copy()
dic2[3] += 2
print(dic["key1"], dic[3], type(dic), len(dic), str(dic))
print(dic2["key1"], dic2[3], type(dic2), len(dic2), str(dic2))
for key in dic2:
print(key, dic2[key])
Math Operation
num = 3
num /= 2 # 1.5
num **= 2
print(num // 1) # 2.0 向下取整
Control flow
# 2 6 8
for i in range(5, 10): # range(len, step)
if i % 2 == 0:
print(i)
elif i % 2 == 1:
continue
while True:
pass
match
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
Function
可以为参数指定默认值,需要注意的是: 默认值只计算一次
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
reply = input(prompt)
if reply in {'y', 'ye', 'yes'}:
return True
if reply in {'n', 'no', 'nop', 'nope'}:
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
# 关键字 参数必须跟在 必选参数 后面
ask_ok('Are you ok?')
ask_ok('Are you ok?', 2)
ask_ok('Are you ok?', 2, 'OK?')
ask_ok('Are you ok?', 2, 'OK?')
ask_ok("Are you ok?", reminder="OK?")
可变参数
def write_multiple_items(file, separator, *args):
file.write(separator.join(args))
Lambda
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
f(0) # 42
f(1) # 43
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
Module
可以使用 import
导入模块,模块中的语句在第一次 import 时执行
# fibo 模块中有 fib(n) 函数
import fibo
fibo.fib(1000)
Package
package 是 Python 构造命名空间的一种方式,可以在文件夹中创建 __init__.py
文件来将该文件夹作为 package
在 __init__.py
中可以定义 __all__
来将模块导出,此时使用 from package import *
时会按照 __all__
中的定义导出
__all__ = ["pkg1", "pkg3", "pkg5"]
需要注意的是,如果 module name 与 __init__
中定义的函数名冲突,就不会导出该 module,因为他被该函数覆盖了
Class
class Animal:
is_animal = True # shared by all instance
def __init__(self, name):
self.name = name # unique to each instance
def __str__(self) -> str:
return str(self.is_animal) + " " + self.name
a1 = Animal("cat")
print(a1) # True cat
a2 = Animal("dog")
print(a2) # True dog
a2.is_animal = False
print(a1, a2) # True cat False dog
继承
class Cat(Animal):
def __init__(self) -> None:
super().__init__("cat")