记录python的一些基础语法,用于查阅
l = [1, 2, 3, 4]
tup = (1, 2, 3, 4)
list((1, 2, 3))
[1, 2, 3]
l.count(3)
l.index(7)
l.reverse()
l.sort()
l.append(4)
# extend会将里面的元素添加进去,而append会直接将[1,2]作为一个元素加入
l.extend([1,2])
tuple([1, 2, 3])
(1, 2, 3)
tup.count(3)
tup.index(7)
list(reversed(tup))
sorted(tup)
本质就是hash表
# 初始化
d1 = {'name': 'jason', 'age': 20, 'gender': 'male'}
d2 = dict({'name': 'jason', 'age': 20, 'gender': 'male'})
d3 = dict([('name', 'jason'), ('age', 20), ('gender', 'male')])
d4 = dict(name='jason', age=20, gender='male')
d1 == d2 == d3 == d4
True
# 赋值
d['name']= 'xiaoming'
# 获取值
d['name']
d.get('name')
d.get('name', 'null')
# 删除
d.pop('name')
# 是否存在
'name' in d
True
# 排序
d = {'b': 1, 'a': 2, 'c': 10}
d_sorted_by_key = sorted(d.items(), key=lambda x: x[0]) # 根据字典键的升序排序
d_sorted_by_value = sorted(d.items(), key=lambda x: x[1]) # 根据字典值的升序排序d_sorted_by_key
# 初始化
s1 = {1, 2, 3}
s2 = set([1, 2, 3])
s1 == s2
True
# 基操
s.add(4)
s.remove(1)
sorted(s)
# 一样的
'123'
"123"
"""123"""
name = 'jack'
name[0]
name[1:3]
# 遍历
for char in name
print(char)
# 替换
s.replace('h', 'n')
# 连接
s += 'a'
'-'.join(['aaa','bbb'])
# 分离
'1-1-1-1-2'.split('-')
# 去掉开头结尾
string.strip(str)
string.ltrip(str)
string.rtrip(str)
# 从开始到结尾进行查找
string.find(sub, start, end)
# 数字到字符串,字符串到数字
str(1)
int('1')
# 格式化
>>> print('id: {}, name: {}'.format("1", "xiaowang"))
id: 1, name: xiaowang
name = input('your name:')
with open('in.txt', 'r') as fin:
text = fin.read()
with open('out.txt', 'w') as fout:
fout.write('123')
# 序列化对象为json字符串
json.dumps(params)
# 反序列化json字符串
json.loads(params_str)
if id == 0:
print('red')
elif id == 1:
print('yellow')
else:
print('green')
l = [1, 2, 3, 4]
# 遍历元素
for item in l:
print(item)
# 遍历下标
for index in range(0, len(l)):
if index < 5:
print(l[index])
# 下标和元素同时需要,使用enumerate
for index, item in enumerate(l):
if index < 5:
print(item)
# while当然也可以
while index < len(l):
print(l[index])
index += 1
# 单行操作,很简洁
expression1 if condition else expression2 for item in iterable
for item in iterable:
if condition:
expression1
else:
expression2
expression1 for item in iterable if condition
for item in iterable:
if condition:
expression1
try:
s = input('please enter two numbers separated by comma: ')
num1 = int(s.split(',')[0].strip())
num2 = int(s.split(',')[1].strip())
...
except ValueError as err:
print('Value Error: {}'.format(err))
finally:
print('finally')
print('continue')
...
except (ValueError, IndexError) as err:
# OR
except ValueError as err:
print('Value Error: {}'.format(err))
except IndexError as err:
print('Index Error: {}'.format(err))
except:
print('Other error')
# 自定义异常
class MyInputError(Exception):
"""Exception raised when there're errors in input"""
def __init__(self, value): # 自定义异常类型的初始化
self.value = value
def __str__(self): # 自定义异常类型的 string 表达形式
return ("{} is invalid input".format(repr(self.value)))
try:
raise MyInputError(1) # 抛出 MyInputError 这个异常
except MyInputError as err:
print('error: {}'.format(err))
# 不需要申明类型
def my_sum(a, b):
return a + b
# 设置默认值
def func(param = 0):
# 函数定义嵌套,内部函数无法被外部直接调用
def f1():
print('hello')
def f2():
print('world')
f2()
f1()
def outer():
x = "local"
def inner():
nonlocal x # nonlocal 关键字表示这里的 x 就是外部函数 outer 定义的变量 x
x = 'nonlocal'
print("inner:", x)
inner()
print("outer:", x)
outer()
# 输出
inner: nonlocal
outer: nonlocal
# 闭包,就是返回一个函数而已
def nth_power(exponent):
def exponent_of(base):
return base ** exponent
return exponent_of # 返回值是 exponent_of 函数
square = nth_power(2) # 计算一个数的平方
cube = nth_power(3) # 计算一个数的立方
lambda argument1, argument2,... argumentN : expression
square = lambda x: x**2
square(3)
# map函数,对于集合内每个元素都做一次func
l = [1, 2, 3, 4, 5]
new_list = map(lambda x: x * 2, l) # [2, 4, 6, 8, 10]
# filter函数,对于集合内每个元素都做一次func,并返回true或者false,结果返回为true的集合
l = [1, 2, 3, 4, 5]
new_list = filter(lambda x: x % 2 == 0, l) # [2, 4]
# reduce函数,集合内每个元素都做一次func,最后将结果组合
l = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, l) # 1*2*3*4*5 = 120
class Document():
WELCOME_STR = 'Welcome! The context for this book is {}.'
def __init__(self, title, author, context):
print('init function called')
self.title = title
self.author = author
self.__context = context
# 类函数
@classmethod
def create_empty_book(cls, title, author):
return cls(title=title, author=author, context='nothing')
# 成员函数
def get_context_length(self):
return len(self.__context)
# 静态函数
@staticmethod
def get_welcome(context):
return Document.WELCOME_STR.format(context)
empty_book = Document.create_empty_book('What Every Man Thinks About Apart from Sex', 'Professor Sheridan Simove')
print(empty_book.get_context_length())
print(empty_book.get_welcome('indeed nothing'))
########## 输出 ##########
init function called
7
Welcome! The context for this book is indeed nothing.
# 引入utils包下的util文件的get_sum方法
from utils.utils import get_sum
# 直接从项目根目录中导入,并依次向下导入模块 mat.py 中的 Matrix
from proto.mat import Matrix
import module_name
from module_name import *