Python3 数据类型&运算符
注:命名(标识符)
项目名、包名、模块名、类名、变量名、函数名
- 字母、下划线、数字,不要以数字开头
- 见名知意:不同字母和数字之间用下划线隔开
- 项目名、包名、模块名、函数名、变量名: 都是小写字母,不同字母之间用下划线隔开
- 类名:首字母大写 如:StudentInfo
- 不要使用关键字命名,
- l 1& 0和o,尽量不要使用不易区分的字母
Python3 标准数据类型
Number : 不可变类型
String : 不可变类型
Tuple : 不可变类型
List : 可变类型
set : 可变类型
Dictionary : 可变类型
1. Number
Python3 中Number支持:int、float、bool、complex(pyhton2 还支持Long)
None(空值)
其他,bool类型(True相当于1, False相当于0)
浮点型float
- 十进制形式
- 科学计数法:5.12e3(即 5.12 X 10的2次方)
浮点数精度问题
>>> 0.1+0.2
0.30000000000000004
>>> 0.1+0.1+0.1-0.3
5.551115123125783e-17
>>> 0.1+0.1+0.1-0.2
0.10000000000000003
>>>
支持浮点数运算的所有编程语言中,都存在的
优化:使用decimal
模块
>>> import decimal
>>> a = decimal.Decimal(0.1)
>>> b = decimal.Decimal(0.2)
>>> print(a+b)
0.3000000000000000166533453694
>>> 0.1+0.2
0.30000000000000004
>>>
相对于普通运算结果,使用decimal
更精准;fractions
模块比decimal
模块更为精准
查询类型
type(x)
isinstance(x,int),返回True,则类型相同;False,则类型不同
(python2中没有布尔型,用数字0表示False,用1表示True)
数值除法:/ 返回一个浮点型,//返回一个整数
Python 3.7.4 on win32
>>> 4/2
2.0
>>> 4//2
2
>>>
- int
- float
- complex
数据类型转换:
complex(x),将x转换为一个复数,实部为x,虚数部分为0
complex(x,y) = x+y j
数字函数:
python3不支持cmp(x,y)
> python3 输入与输出
> 1. print() 输出
> 2. input() 输入
>>> name=input()
>>> print(name)
python3
>>> print('hello,',name) ('hello,', 'python3!')
>>>
- 空值:None
-
2. string
注:序列,一块可存放多个值的连续内存空间,这些值按一定顺序排列,可以通过每个值所在位置的编号即索引访问他们。
在Python中,序列类型包括:字符串、列表、元组、集合、字典,但集合和字典不支持索引、切片、相加和相乘操作。
# 序列支持的内置函数
len( x)
max()、min()
list()、str()
sum()
sorted()
reversed() # 反序
Python中没有单独的字符类型,一个字符就是长度为1的字符串
\转义字符,使用r 可以让反斜杠不发生转义
逆向取值
>>> print(s)
it
>>> s = r'it\n'
>>> print(s)
it\n
>>>
编码
- 编码与解码
- 字符编码
Unicode字符集,又称万国码、国际码、统一码;因乱码而存在
Unicode字符集可以使用的编码方案有三种:- UTF-8 ,使用最广泛
- UTF-32
- UTF-16
>>> import sys
>>> sys.getdefaultencoding() # Python 3.0+ 默认字符编码
'utf-8'
>>>
bytes
python 3新增了bytes类型,用于代表字节串
-
string
:由多个字符组成,以字符为单位进行操作 -
bytes
: 由多个字节组成,以字节为单位进行操作
注:字节(如二进制格式)、字符
计算机基础概念:
位bit、字节Byte ,8bit = 1Byte
其中4位可以用一个16进制表示,每个字节需要2个16进制表示 -
bytes(str,encoding='utf-8') & str.encode('utf-8')
: 将字符串转为字节串
若不指定字符集,则按照UTF-8
>>> a=bytes('我',encoding='utf-8')
>>> a
b'\xe6\x88\x91'
decode解码
# 将bytes对象解码成字符串,默认使用UTF-8解码
>>> a.decode('utf-8')
'我'
>>>
python3中,字符串编码类型是Unicode
注:
动态语言:变量本身不固定
静态语言:定义变量时需要指定变量类型,若赋值时不匹配,则报错
>>> chr(200)
'È'
>>> ord('È')
200
>>>
ord(character)
character 长度是1的字符串
返回该character对应的值
超出定义范围则报错
chr(number)与 ord(c)相反
Python字符串类型是str,在内存中以Unicode表示,一个字符对应若干个字节。
在网络传输或存储磁盘时,需要把str变为以字节为单位的bytes。
Python对bytes类型的数据用带b前缀的单引号或双引号表示。
转义字符\
>>> s='1234\
sad happy!'
>>> s # 在行尾时,作为续行符
'1234sad happy!'
>>> s='It\'s great!'
>>> s
"It's great!"
>>> s="I say,\"How are you!\""
>>> s
'I say,"How are you!"'
Python 字符串运算符
+、*、s[1]、s[1:]、in\not in
r或R 原始字符串,转义字符不生效
sname[start : end : step] # step间隔
>>> s=r"I say,\"How are you!\""
>>> s
'I say,\\"How are you!\\"'
>>> s="I say,\"How are you!\""
>>> s
'I say,"How are you!"'
>>>
字符串格式%+format()
https://www.cnblogs.com/fat39/p/7159881.html
%s 格式化字符串
%e 科学计数法
%d 格式化整数
字符串内建函数
- s.count(str,beg=0,end=len(string))
返回str在s中出现的次数 - s.find(str,beg=0,end=len(string))
返回str在s中首次出现的索引值;没有则返回-1 - s.index(str,beg=0,end=len(string))
返回str在s中首次出现的索引值;没有则报错 - s.join(seq)
以指定字符串s作为分隔符,将seq中所有元素(需字符串)合并为一个新的字符串
>>> s
'you come from China!'
>>> L=[1,2,3]
>>> s.join(L)
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
s.join(L)
TypeError: sequence item 0: expected str instance, int found
>>> L=['1','2','3']
>>> s.join(L)
'1you come from China!2you come from China!3'
>>>
- s.split(str='',num=s.count(str))
str分隔符,默认所有的空字符
num 分割次数。默认-1,即分割所有
返回:分割后的字符串列表
>>> s.join(L)
'1you come from China!2you come from China!3'
>>> s2=s.join(L)
>>> s2.split(s)
['1', '2', '3']
3. list
类似数组,但比数组占优势,数组需要存储数据类型一致
L[start_index:end_index:interval]
interval间隔,包含start_index,不包括end_index
逆向取值
>>> L=[1,complex(3,4),2.1,True,'a',[4,5],(6,7),{1:'bc'}]
>>> print(L)
[1, (3+4j), 2.1, True, 'a', [4, 5], (6, 7), {1: 'bc'}]
>>> L[1:6:2]
[(3+4j), True, [4, 5]]
>>>
删除列表元素
del list[2]
#删除list[2]
实际开始时,del 语句不常用,因为 Python 自带的垃圾回收机制会自动销毁不用的列表,所以即使开发者不手动将其删除,Python 也会自动将其回收。
max(list)
# 返回列表元素最大值(按id大小比较)
min(list)
# 返回列表元素最小值
list(seq)
# 将seq序列转换为list
-
list.count(obj)
# 统计某元素在列表中出现的次数 -
list.index(obj)
# 从列表中找出某个值第一个匹配的索引位置 -
list.extend(seq)
# 在列表末尾一次性追加另一个序列中的多个值 -
list.append(obj)
# 在列表末尾添加一个新的对象 -
list.insert(index,obj)
# 将对象插入指定位置;不在序列中则报错
>>> L.index(0)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
L.index(0)
ValueError: 0 is not in list
-
list.pop([index=-1])
# 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
>>> L = [1, 'wang', 1.2, [], 'li', {1: 3}]
>>> L.pop()
{1: 3}
>>> L
[1, 'wang', 1.2, [], 'li']
>>> L.pop(0)
1
>>> L
['wang', 1.2, [], 'li']
>>>
-
list.remove(obj)
# 移除列表中某个值的第一匹配项
或del list[index] # 删除指定位置的元素 -
list.reverse()
# 反向列表中元素 -
list.sort(key=None,reverse=False)
# 对原列表进行排序
TypeError: '<' not supported between instances of 'str' and 'list'
-
list.clear()
# 清空列表 -
list.copy()
#复制列表,类似与L2=L;返回复制后的新列表
4. tuple
特殊元组:0或1元素
>>> tup1=() # 空元组
>>> print(tup1)
()
>>> tup2=(1,) #一个元素的元组,需要在元素后添加逗号
>>> print(tup2)
(1,)
>>> tup3=(1)
>>> print(tup3)
1
>>>
tuple并不是严格意义上的不可修改
- 对元组重新赋值
>>> tuple1=(1,)
>>> tuple1
(3, 4)
>>>
- 连接多个元组
>>> tuple1=(1,)
>>> tuple1 = tuple1 +(3,4)
>>> tuple1
(1, 3, 4)
>>>
- 嵌套式的
>>> tuple1=(1,2,[3,4])
>>> tuple1
(1, 2, [3, 4])
>>> tuple1[2][0]='wang'
>>> tuple1
(1, 2, ['wang', 4])
>>>
5. set
set()或{value0……}创建集合
set()空集合
{}空字典
set_v=set(iterable) <=> set_v ={value}
-差集
|并集
&交集
^ 不同时存在的元素即:(a|b)-(a&b)
>>> set_v ={1}
>>> type(set_v)
<class 'set'>
>>> set_v = set(1)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
set_v = set(1)
TypeError: 'int' object is not iterable
>>> set_v = set(tup2)
>>> print(set_v)
{1}
>>>
del tuple_name
# 删除字典
s = {1, 2, 3, 'wang'}
s.add(7.9) # 添加元素
s.update(['Li', 4], {3: 90}, ('tuple1',), {0.2, 1.1})
# s.remove('1') # KeyError: '1' 元素不存在
s.remove(1)
s.discard(1) # 不存在也不保错
s.pop() # 随机删除一个元素
print(len(s))
s.clear() # 清空集合
if 3 in s:
print('YES')
else:
print('NO')
6. Dictionary
key键值必须是不可变类型,同一字典中,key是唯一的
python3中数据类型转换
int(x)、float(x)、complex(real[,imag])、tuple(x)、list(x)、set(x)、dict(x)
repr(x) 转为表达式字符串
str(x) 转为字符串
chr(x) 将一个整数转换为一个字符、
ord(x) 将一个字符转换为它的整数值
hex(x) 十六进制、oct(x) 八进制
# -*- coding:utf-8 -*-
"""
@author:wlh
@file:0910_dict&set.py
@time:2019/09/10
"""
dict2 = {1: 'one', 2: [123, 4]}
print('dict2 = ', dict2)
# print(dict2[3]) # KeyError: 3
del dict2[1]
print('del key&value : ', dict2)
# print(dict[1]) # TypeError: 'type' object is not subscriptable
dict2.clear() # 清空dict
print('After clear() : ', dict2)
del dict2
# print(dict2) # NameError: name 'dict2' is not defined
# dict2 = {[1, 2]: 'one'} # TypeError: unhashable type: 'list'
# dict2 = {{1: 2}: 'one'} # TypeError: unhashable type: 'dict'
dict2 = {1: 1, 1: ['two', 2]}
print('dict2 = ', dict2) # 创建时如果同一个键被赋值两次,后一个值会被记住
print('--------深复制&浅复制---------')
dict3 = dict2.copy() # 浅复制:深拷贝父级对象(一级目录),子对象(二级对象)不拷贝,还是引用
dict4 = dict2 # 引用对象
print(' dict4 = ', dict4)
print('dict2.copy() = ', dict3)
print('--------一级目录增删改---------')
dict2[3] = 'three'
print(' dict2 = ', dict2)
print('dict2.copy() = ', dict3)
print(' dict4 = ', dict4)
print('--------二级目录增删改---------')
dict2[1].remove(2)
print(' dict2 = ', dict2)
print('dict2.copy() = ', dict3)
print(' dict4 = ', dict4)
7. Python 缓冲机制
是为提高程序执行的效率服务的,实际上就是在 Python 解释器启动时从内存空间中开辟出一小部分,用来存储高频使用的数据,这样可以大大减少高频使用的数据创建时申请内存和销毁时撤销内存的开销。
id(X)
查询内存地址
8. python3 输入与输出
python 3 input()
<==>
python 2 中,raw_input()
- print()
Python3 运算符
1. Python3 算法运算符
+、-、*
、/、%、**
(幂)、//(整除)、
2. Python3 比较运算符
==、!=、>、<、>=、<=
返回True或False
3. Python3 赋值运算符
>>> c=3 #简单赋值=
>>> a=2
>>> c+=a # 加法赋值+=,即c=c+a
>>> print(c)
5
>>> c-=a # 减法赋值-=,即c=c-a
>>> print(c)
3
>>> c*=a # 乘法赋值*=,即c=c*a
>>> c
6
>>> c/=a # 除法赋值/=,即c=c/a
>>> c
3.0
>>> c%=a # 取模赋值%=,c=c%a 余数
>>> c
1.0
>>> c*=a
>>> c
2.0
>>> c=4.0
>>> c**=a # 幂赋值 c=c**a,即c的a次幂
>>> c
16.0
>>> c=16
>>> c//=a # 取整除赋值 c=c//a,即整除取商
>>> c
8
>>> c=7.5
>>> c//=a
>>> c # 整除且保留字符类型
3.0
>>>
4. Python3 逻辑运算符
and or not
5. Python3 成员运算符
in \not in
6. Python3 身份运算符
is\ is not
判断引用是否是一个对象
7. Python3 位运算符
按位运算符把数字看作二进制来进行计算
&
按位与:相应位均是1,结果为1
|
按位或:对应位有1时,结果为1
^
按位异或:相异,结果为1
~
按位取反,0变1&1变0,单运算符
<<
左移,底位补0
>>
右移
>>> a=90
>>> b=11
>>> bin(a) # bin(整型)
'0b1011010'
>>> bin(b)
'0b1011'
>>> a&b # 0b1010
10
>>> a|b # 0b1011011
91
>>> a^b # 0b1010001
81
>>> ~a # ???
-91
>>> a<<2 # a*2的n次幂
360
>>> a>>2 # a//(2的n次幂),整除
22
>>>
8. Python3 运算符优先级
优先级:依次从高到低
**
指数
~、+、-
:以元运算符
* 、/、 % 、//
+ 、-
>> 、<<
按位与:&
位运算:^
、|
比较
等于运算符:<> 、==、 !=
赋值
身份
成员
逻辑
9. 三元运算符
True_statements if expression else False_statements
等同于:
if expression:
print(True_statements)
else:
print(False_statements)
网友评论