Python笔记② 变量与操作
前言
记录学习内容,希望便于查阅
一,变量的规则
不同的变量有不同的规则,没有规矩不成方圆,正因为有了这些统一的规则,才能使代码按照我们设计的思路工作!
1,变量的本质
Python中实际变量的本质是对象
Python的对象模型(类)由3部分组成:身份(指针)、类型、值
- 身份:用来标识对象的唯一标识。可调用函数id查看
- 类型:用来表明对象可以存放的类型。可调用函数type查看
- 值:对象储存的具体数值。可直接查看
2,变量演示(例子)
val1,val2,val3 = 6,3.1415926,'hello' #一条语句中可定义多个变量,用逗号隔开既可
#分别使用print输出各个值的属性
print("指针:",id(val1) ,"类型:",type(val1) ,"值:",val1 )
print("指针:",id(val2) ,"类型:",type(val2) ,"值:",val2 )
print("指针:",id(val3) ,"类型:",type(val3) ,"值:",val3 )
输出:
指针: 1752460928 类型: <class 'int'> 值: 6
指针: 2775148741592 类型: <class 'float'> 值: 3.1415926
指针: 2775147670920 类型: <class 'str'> 值: hello
3,变量类型
接下来会一一进行简单的介绍

4,变量帮助函数
二,number(数字)类型
1,算数运算符
| Arithmetic operators | Description |
|---|---|
| + | 加 |
| - | 减 |
| * | 乘 |
| / | 除(会产生浮点数) |
| % | 取模(余数) |
| ** | 幂(次方) |
| // | 整除(无浮点数产生) |
| abs(x) | 绝对值 |
| int(X,[base]) | 将X转换成整形, |
| float(X) | 将X转换成浮点型 |
| complex(re,im) | 生成负数 |
| c.conjugate() | 取c的共轭复数 |
| divmod(x,y) | 返回商和余数 |
2,赋值运算符
| Assignment Operators | Description |
|---|---|
| += | 加 |
| -= | 减 |
| *= | 乘 |
| /= | 除 |
| %= | 取模 |
| **= | 幂 |
| //= | 取整除 |
3,比较运算符
| Comparison operator | Description |
|---|---|
| == | 等于 |
| != 或 <> | 不等于 |
| > | 大于 |
| < | 小于 |
| >= | 大于等于 |
| <= | 小于等于 |
| is | 指针等于 |
| is not | 指针不等于 |
4,Python的缓存规则
Python会根据对象的读取频繁程度以及内存占用其概况来考虑,按照一定规则把某些对象存入缓存中,如下表
| 对象 | 是否需要重新创建 | 生效范围 |
|---|---|---|
| 范围在[-5,256]之间的小整数 | 如果曾经传见过,直接存入缓存,不再重新创建 | 全局 |
| 字符串对象 | 同上 | 同上 |
| 大于256的整数 | 改代码块创建过就直接存入缓存,不才重新创建 | 改代码块 |
| 大于0的浮点型对象 | 同上 | 同上 |
| 小于0的浮点型对象 | 不进行缓存,每次都需要额外创建 | |
| 小于-5的整数 | 同上 |
5,bool运算符
| Boolean operators | Description | Additional explanation |
|---|---|---|
| and | 取“与” | 短路运算符 |
| or | 取“或” | 短路运算符 |
| not 或 ! | 取“反” | 优先级低 |
6,位运算符
| Bitwise Operators | Description |
|---|---|
| & | 位“与” |
| | | 位“或” |
| ^ | 位“异或” |
| ~ | 位反“ |
| << | 位左移 |
| >> | 位右移 |
三,string(字符串)类型
1,字符串分类
- 单行字符串:用单引号(’ ')、双引号(" ")表示
- 多行字符串(块):用三单双引号(’’’ 、""" )表示
2,转义字符
(1)常用转义字符汇总
| Escape characters | Description |
|---|---|
| \ | 续行符 |
| \\ | 反斜杠符号 |
| \’ | 单引号 |
| \" | 双引号 |
| \a | 响铃 |
| \b | 退格 |
| \e | 转义 |
| \000 | 空 |
| \n | 换行 |
| \v | 纵向制表符 |
| \t | 横向制表符 |
| \r | 回车 |
| \f | 换页 |
| \oyy | 八进制ASCIIyy字符 |
| \xyy | 十六进制ASCII字符 |
| \other | 其他格式以普通字符输出 |
(2)原字符串(raw string)
不让" \ "产生转义的作用
- 字符串前加r或R
- 使用repr()函数处理字符串
(3)编码
- 寒假再补,快考试了,抱歉
3,print与占位符
(1)查看print
q = dir(print)
print(q)
print('%'*30)
help(print)
#输出如下
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
(2)占位符
| Placeholder | Description |
|---|---|
| %s | 字符串 |
| %r | 无转移功能的字符串 |
| %c | 单个字符 |
| %b | 二进制整数 |
| %d | 十进制整数 |
| %o | 八进制整数 |
| %x | 十六进制整数 |
| %e | 指数(基底写成e) |
| %E | 指数(基底写成E) |
| %f | 浮点数,一般写成%m.nf,m代表总长、n代表小数点后几位 |
| %F | 同上 |
| %g | 指数或浮点数 |
| %G | 指数或浮点数 |
4,用字符串演示“序列”的运算与操作(例子)
- 寒假再补,快考试,时间有些紧,抱歉
5,有关字符串的相关函数
| String manipulation functions | Description |
|---|---|
| len() | 求序列长度 |
| in: | 判断元素是都在序列中 |
| max() | 返回字符编码的最大值 |
| min() | 返回字符编码的最小值 |
| cmp(str1,str2) | 判断两个序列是否相同 |
| ord() | 由字符返回单个字符的字符编码 |
| chr() | 由单个字符编码返回字符 |
| str.split() | 将字符串根据某个分隔符进行分割 |
| chr.join() | split的逆操作 |
| str.title() | 首字母大写 |
| xxxxxxx | 等等 |
同print的查看方式,用dir查看string的方法,用help看具体介绍
q = dir(str)
print(q)
print('%'*30)
#. + 一个具体的方法可查看对应的方法,不加则看所有的方法
help(str.__add__)
#输出如下:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Help on wrapper_descriptor:
__add__(self, value, /)
Return self+value.
四,list(列表)类型
1,list介绍
Python中使用最频繁的数据类型。它是一个有序集合。
list中的元素的类型可以互相不同,并且可以互相嵌套
2,list内置函数
| List built-in functions | Description |
|---|---|
| list.append() | 在尾部增加一个元素 |
| list.extend() | list + list |
| list.insert(i,x) | 在索引i前插入元素x |
| list.index(x) | 返回value为x的索引 |
| list.remove(x) | 删除value为x的元素 |
| list.pop(i) | 弹出(删除)索引为i的元素 |
| list.clear() | 删除列表中的所有项 |
| del list[i 或 切片] | 删除索引元素或切片 |
| list.count(x) | 计算value为x出现的次数 |
| list.sort() | 列表排序 |
| list.reverse() | 逆序操作 |
3,list实现队列和栈(例子)
4,更高效的队列:使用deque结构体(例子)
5,列表筛选:使用filter函数(例子)
五,tuple(元组)类型
1,Tuple介绍
可以这样理解:tuple(元组)是list(列表)的只读版
不同之处:tuple(元组)的元素不能修改
2,Compare tuple with list
tuple的操作与list非常相似,内部元素可以是任意类型,并且可以互相嵌套
q = dir(tuple)
print(q)
print('%'*30)
#. + 一个具体的方法可查看对应的方法,不加则看所有的方法
help(tuple.__add__)
输出如下:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Help on wrapper_descriptor:
__add__(self, value, /)
Return self+value.
3,Summary
tuple:list的只读版本,不过由于tuple的不可改变的特性,作为返回值时,可以让代码更加稳定
六,set(集合)类型
作用:进行成员关系的测试和消除重复元素。
1,set介绍
set是一个无序、不重复元素的集合
2,set运算
set运算与数学中的集合运算类似,支持交并差等操作
3,set内置函数
q = dir(set)
print(q)
print('%'*30)
#. + 一个具体的方法可查看对应的方法,不加则看所有的方法
help(set.__and__)
输出如下:
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Help on wrapper_descriptor:
__and__(self, value, /)
Return self&value.
4,frozenset(不可变集合)
frozenset与set的关系 和 tuple与list的关系 类似
frozenset里的值不能被改变
七,dictionary(字典)类型
1,字典介绍
dictionary是一种映射类型(mapping type),内部元素以键值对的方式出现
2,字典内置函数
| Dictionary built-in functions | Description |
|---|---|
| dict.fromkeys(seq[,value] ) | 创建新的字典 |
| dict.get(key[,default=None]) | 返回指定键key的值value |
| dict.setdefault(key,default-None) | 类似get,但若无键key则添加进dict |
| del | 删除指定的键值对 |
| dict.clear() | 清除字典中的所有元素 |
| dict.item() | 以列表的形式返回元组(键:值)数组 |
| len(dict) | 返回字典中俄的元素个数 |
| in | 判断key是否在dict中 |
| not in | 与上面相反 |
| dict.key() | 返回字典中的所有key |
| dict.value() | 返回字典中的所有value |
| dict.update(dict1) | 更新dict1中的键值对到dict里 |
八,深拷贝与浅拷贝
1,浅拷贝
只用了内容,并未创建新的对象,未分配新的内存
2,深拷贝
复制了内容,创建了新的对象,分配了新的内存
3,浅例子
#Deep and shallow copy
list_1 = [[1,2],'hello']
list_equal = list_1
print(id(list_1),' ',id(list_equal)) #list_equal与list_1用同一个地址浅拷贝
list_equal = list(list_1) #创建一个新的list对象
print(id(list_1),' ',id(list_equal))#给list_equal分配新地址
输出如下:
2072284919944 2072284919944
2072284919944 2072284919048
本文深入讲解Python中的变量、数字、字符串、列表、元组、集合、字典等数据类型的使用规则与操作方法,包括算术运算、比较运算、位运算等,以及数据类型的内置函数和操作示例。
265

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



