区分大小写。一般使用大驼峰或_
函数内使用global修改变量, 作用域为全局
*收集参数(可变参数)
nonlocal标识变量是上一级函数中的局部变量
reverse 永久反转. sorted 临时反转
1、数据类型
查看内置函数: dir(类型),如 dir(dict)
查看数据类型 type()
a=None
type(a)
<class 'NoneType'>
Number:int,float,complex
String
bool:True,False
-
list(列表),[]
下标从0开始,-1代表最后一个元素
查看长度: len(list_str)
追加元素: list_str.append(‘a’)列表推导式: [运算 for i in range(变量)]
//对嵌套列表赋值
s = [[0] * 3 for i in range(3)]
print(s) #[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
s[1][1] = 1
print(s) #[[0, 0, 0], [0, 1, 0], [0, 0, 0]]
//二维列表降维
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flatten = [col for row in matrix for col in row]
print(flatten) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
list = [1, 2, 3]
list.insert(1, [4, 5])
print(list)
for i, v in enumerate(list):
print(i, v)
di = dict([(1, 2), (3, 4)])
- tuple(元组),自身元素不可变,自身元素的子元素可变,()可以省略
一个元素的定义: b=(1,)
元素为list时,list的子元素可变,引用
b=(1) # 类型为int - dictionary(dict,字典),无序集合,{},kv格式
查找和插入速度快,占用内存多
c={}
查找元素是否在字典中in: ‘a’ in c
d = {‘a’:12,‘b’:11}
使用get查找:d.get(‘c’,-1) ,不存在是输出指定值。不指定时不存在输出为空
删除元素pop: d.pop(‘b’,-1) - set(集合),无序不重复
可以使用{}或set()创建,空set使用set()创建
集合之间可以进行:-差集 &交集 |并集 ^反交集
自动过滤重复元素
s=set([1,2,3])
s = set([11,1,1,2,3]) 输出:{3, 1, 2, 11}
添加元素add:s.add(4)
移除元素remove:s.remove(1)
Fraction(1, 3): 有理数. 分数1/3
2、运算符
not 非
// 取整数的商, type仍为原类型
math.trunc(3/2) , 取整为int 类型
3、元素拼接
- 使用 +
- 使用join
list_str=[‘你’,‘好’,‘北’,‘京’]
str=’’.join(list_str)
'你好北京' - 使用format ,{}代表占位符,可以后期赋值
str=‘I love {},because {}’.format(‘python’,‘life is short’)
'I love python,because life is short'
4、字符串反转(使用切片)
a=‘abcdefg’
a[::-1]
输出: ‘gfedcba’
5、字符串操作
lower 用于英文,casefold 还支持其它语言字符
1. 查找下标
-
find,找不到输出-1
a=‘abcdefg’
a.find(‘a’) 输出:0
a.find(‘z’) 输出:-1 -
index,找不到报错
a.index(‘b’) 输出:1 -
替换 replace
-
查找出现次数 count
-
字符串分割 split
6. Python3 * 和 ** 运算符
7. 字符串格式化
% ,
format , {}可以复用 . format()
f(3.6开始支持)
python 3.8 支持=
t = f"I'm {16+2=}"
print(t) #I'm 16+2=18
# 进制转换
t = f"I'm {16:#x}"
print(t)
print(str(r'http:\t\do\table'))
r:原生字符,不会作为转义字符
8. lambda
1.打印10以内的奇数
print(list(filter(lambda x: x % 2, range(10))))
# 一般写法
a = lambda x, y: x * y
print(a(3, 4))
# 排序
users = [{"name": "ziyan"}, {"name": "紫颜"}, {"name": "晓丹"}]
users.sort(key=lambda x: x["name"])
print(users)
9.私有属性和方法
构造函数:__init__()
私有函数: __fin()
10.装饰器函数
外围函数,内嵌函数,return 内嵌函数(不加(),即不执行)

def check_str(func):
def inner(*args, **kwargs):
result = func(*args, **kwargs)
if result == "ok":
return f'result is {result}'
else:
return f'result is faild:{result}'
return inner
@check_str
def test(data):
return data
result = test('no')
print(result) # result is faild:no
- 类的常用装饰器 @classmethod,@staticmethod,@property
class Stu(object):
def __init__(self, name):
self.__name = name
@classmethod
def run(cls):
print("run")
cls.sleep()
def play(self):
print("play")
self.run()
self.sleep()
@staticmethod
def sleep():
print("sleep")
@property
def name(self):
return self.__name
# 修改@property的值
@name.setter
def name(self, value):
self.__name = value
Stu.run()
Stu.sleep()
s = Stu("小仙紫")
result = s.name
print(result)
s.name = "紫颜"
print(s.name)
s.play()
s.sleep()
#查看继承链 类.mro() 或 类.__mro__
print(Stu.mro())
print(Stu.__mro__)
11.class类
- 类的链式调用
class Test(object):
def __init__(self, attr=''):
self.__attr = attr
# 附加属性不存在时,调用
def __getattr__(self, item):
if self.__attr:
item = f'{self.__attr}.{item}'
else:
item = item
print(item)
return Test(item)
# 使类实例对象可以以“对象名()”的形式使用
def __call__(self):
print(f'key is {self.__attr}')
t = Test()
# 遇到‘.’执行getatrr ,遇到'()'执行call,遇到类名() 执行init
t.a.b.c()
2.super
class Student(Stu):
def __init__(self):
# Student当前类 self类的实例.python3 可以省略super里面的内容 __init__()使用父类的方法.
super(Student, self).__init__()
12.异常
raise 抛出指定异常
- 自定义异常类
class NewError(Exception):
def __init__(self, msg):
self.msg = msg
13.包
文件夹下,有__init__.py文件就是包了
导入当前文件同级的包可以用 .包名
pip在python3.4 开始自带
安装指定版本: 包名后加==版本
这篇博客详细介绍了Python中的数据类型,包括Number、String、List、Tuple、Dictionary和Set,以及运算符、元素拼接、字符串反转等操作。还讨论了Python3的*和**运算符、字符串格式化、lambda表达式、私有属性和方法、装饰器函数、class类、异常处理和包的使用。

被折叠的 条评论
为什么被折叠?



