1 数据类型
Python中可以自定义类型,相关内容在类的章节中涉及;本节学习Python中5种标准数据类型,即
- Numbers
- String
- List
- Tuple
- Directionary
python是弱类型语言,变量可以随时使用,不需要提前声明,并且可以改变一个变量指向的数据类型。
1.1 Numbers 数字
数字分为整数、浮点数和复数,都可以使用常用的运算符进行操作;其中需要注意的是
-
复数的初始化方法为
>>> a=1+1j >>> a (1+1j) >>> a**2 2j >>> type(a) <class 'complex'> >>> getsizeof(a) # 返回值为字节 32
-
整数自动拓展,因此精度可范围都可以非常大,并且由下面的例子可以看出,python是通过自动加长其在内存中占的位数实现的
>>> a=1234567890123456789 >>> getsizeof(a) 36 >>> a=1 >>> getsizeof(a) 28
-
float数据类型可能存在精度问题,但是一般来说都是满足要求的,不需要使用专业的包来改善这个问题(会降低速度)
>>> 0.1+0.2 0.30000000000000004
-
布尔类型是一种特殊的整型
# 查看类型,发现其是bool类型 >>> type(True) <class 'bool'> # 但是可以进行整数运算 >>> True+True 2
1.2 List 列表
列表是数组的强化,其可以包含不同类型的数据,甚至是嵌套另一个列表,可以用来管理各种层次结构的数据,其标识符是[]
。例如
>>> a = ["wuyao", 22, "male", [88, 188.5], "18846045346"];
>>> a
['wuyao', 22, 'male', [88, 188.5], '18846045346']
-
访问元素
>>> a[0] #访问单个元素 'wuyao' >>> a[0:2] #访问一段元素(左闭右开区间) ['wuyao', 22] >>> a[2:] #访问某一个开始到结束的元素 ['male', [88, 188.5], '18846045346'] >>> a[1::2] #从某一个开始到某一结束,间隔几个元素取一个元素 [22, [88, 188.5]] >>> a[3][1] #获取子列表中的元素 188.5
-
列表的初始化
# 手动编写 a = ["wuyao", 22, "male", [88, 188.5], "18846045346"]; # 截取已存在的列表 >>> b=a[0::2] # 截取方式可以是访问方式中的任何一种 >>> b ['wuyao', 'male', '18846045346']
-
删除元素
# 已知元素值,使用list对象的成员函数remove >>> a ['wuyao', 22, 'male', [88, 188.5], '18846045346'] >>> a.remove(22) >>> a ['wuyao', 'male', [88, 188.5], '18846045346'] # 已知元素位置,使用del关键字 >>> a ['wuyao', 'male', [88, 188.5], '18846045346'] >>> del a[0] >>> a ['male', [88, 188.5], '18846045346'] # 删除列表末尾元素,使用成员函数pop,同时可以获得末尾元素的值 >>> b=a.pop() #也可以带一个参数,表示弹出倒数第几个元素,从0开始 >>> b '18846045346'
-
查询列表元素个数
>>> a ['wuyao', 22, [88, 188.5], '18846045346'] >>> len(a) 4
-
向列表添加元素
# 向末尾添加元素,使用成员函数append,仅支持一个参数 >>> a ['wuyao', 22, [88, 188.5], '18846045346'] >>> a.append("male") >>> a ['wuyao', 22, [88, 188.5], '18846045346', 'male'] # 使用成员函数extend,支持插入一个列表 >>> a.extend(["19B", 902020]) >>> a ['wuyao', 22, [88, 188.5], '18846045346', 'male', '19B', 902020] >>> a.append(["19B", 902020]) #使用append插入列表后不会合并元素 >>> a ['wuyao', 22, [88, 188.5], '18846045346', 'male', '19B', 902020, ['19B', 902020]] # 在指定位置插入 >>> a.insert(0,'HIT') >>> a ['HIT', 'wuyao', 22, [88, 188.5], '18846045346', 'male', '19B', 902020, ['19B', 902020]]
-
列表支持哪些运算符
# 赋值符 >>> a=['wuyao', 22, [88, 188.5], '18846045346', 'male'] >>> b=a >>> b ['wuyao', 22, [88, 188.5], '18846045346', 'male'] # + * 操作 >>> a+a ['wuyao', 22, [88, 188.5], '18846045346', 'male', 'wuyao', 22, [88, 188.5], '18846045346', 'male'] >>> 2*b ['wuyao', 22, [88, 188.5], '18846045346', 'male', 'wuyao', 22, [88, 188.5], '18846045346', 'male'] # in & not in,会返回真或假 >>> "male" in a True >>> "female" in a False >>> "wuyao" not in a False # 比较运算符 < > >= =< != >>> c=[123,456] >>> b=[234,345] >>> c>b False >>> c<b True >>> c>=b False >>> c!=b True
-
成员函数(也叫内置函数,BIF)
上面已经提到了
append
、extend
、pop
、insert
等列表对象的成员函数,除此之外比较常用的还有>>> a ['wuyao', 22, [88, 188.5], '18846045346', 'male', 'wuyao', 22, [88, 188.5], '18846045346', 'male'] # 统计某元素出现次数 count >>> a.count("wuyao") 2 # 查找某个值在元素列表中第一次出现的位置 index >>> a.index(22) 1 # 此函数具有重载形式,即在列表指定段进行搜索 >>> start=a.index(22)+1 >>> stop=len(a) >>> a.index(22, start, stop) 6 # 反序列表 reverse >>> a.reverse() >>> a ['male', '18846045346', [88, 188.5], 22, 'wuyao', 'male', '18846045346', [88, 188.5], 22, 'wuyao'] # 对列表排序 sort >>> b=[1,4,2,9,5,0] >>> b.sort() >>> b [0, 1, 2, 4, 5, 9] # 默认从小到达 >>> b.sort(reverse=True) # 激活反序后(本质是一个带默认值为True的函数参数),从大到小, >>> b [9, 5, 4, 2, 1, 0]
成员函数可以使用
dir()
函数来查看>>> dir(list) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
dir函数可以查看一个类的全部内容,包括函数、方法、类、变量 help函数可以查看某个函数或方法的帮助文档
-
引用与拷贝
使用一个列表来初始化一个新列表,可以使用以下两种方式
>>> b [9, 5, 4, 2, 1, 0] >>> b=[1,4,2,9,5,0] >>> c = b # 本质是引用 >>> d = b[:] # 真正的拷贝 >>> c [1, 4, 2, 9, 5, 0] >>> d [1, 4, 2, 9, 5, 0] >>> b.sort() # 对b操作 >>> c [0, 1, 2, 4, 5, 9] # c随之改变 >>> d [1, 4, 2, 9, 5, 0] # d不变化
1.3 Tuple 元组
元组的标识符是,
,一般也配合使用()
。
-
创建
>>> a (1, 2, 3, 6, 5, 4) >>> type(a) <class 'tuple'>
-
访问上和List没有区别
-
添加、插入等操作没有List零活
-
通过
dir()
来查看其成员函数,发现其仅支持count
和index
。>>> dir(tuple) ['__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'] >>> a.count(1) 1 >>> a.count(9) 0 >>> a.index(1) 0 >>> a.index(9) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: tuple.index(x): x not in tuple
1.4 String 字符串
通常使用'...'
、"..."
、"""..."""
、'''...'''
将需要表示的字符串围起来。需要注意的转义字符的问题和C/C++大同小异。
-
字符串元素访问
str = "Knowledge is power!" >>> str[0] 'K' >>> str[3:5] 'wl' >>> str[1:8:2] 'nweg'
-
字符串初始化与List差不多
# 手动方式 str = "Knowledge is power!" # 使用已存在的字符串来初始化 >>> new=str[:] >>> new 'Knowledge is power!'
-
字符串连接
字符串连接非常灵活
>>> a = "wu" "yao" # 直接连接 >>> a 'wuyao' >>> b = "hello " >>> b+a 'hello wuyao'
-
内置方法
可以发现字符串类型对象的内置函数非常多
>>> dir(str) ['__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', 'isascii', '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']
可以稍作了解,需要时知道有就可以了。
1.5 序列
可以发现list
、tuple
、string
都具有以下特点
- 可以通过索引来获取一个元素的值
- 默认索引值是从0开始
- 有一些共同的操作
因此将其统称为序列,下面介绍序列的常用BIF。
-
list([iterable])
将一个可迭代对象转换为列表
>>> list("wuyao") ['w', 'u', 'y', 'a', 'o'] >>> list((1,2,3)) [1, 2, 3]
-
tuple([iterable])
将一个可迭代对象转换为元组
>>> tuple("wuyao") ('w', 'u', 'y', 'a', 'o')
-
str(obj)
-
len(sub)
返回元素数量
-
max()
返回最大值,可以对字符串操作
>>> a="wuyao" >>> max(a) 'y' >>> min(a) 'a' >>> a="123sdf" # 应该是比较ascii码大小 >>> max(a) 's'
-
min()
返回最小值
>>> a=[ 1, 3, 5, 8] >>> min(a) 1
-
sum(iterable[, start])
从指定位置开始求和(默认为0位置),只支持数字
-
sorted(iterable, key = None, reverse =False)
排序
-
resersed(sequence)
反序
-
enumerate(iterable)
-
zip(iter1 [, iter2 […]])
1.6 dict 字典
dict类型和json类似,具有键值对(key-value)的特点。其格式为
{keyname1 : value1, keyname2 : value2, ......, keynamen": valuen}
---
>>> a={"key1" : 1, "key2" : "two"}
>>> a
{'key1': 1, 'key2': 'two'}
>>> type(a)
<class 'dict'>
键名和值的类型都可以是数字、字符串等基本类型。
-
初始化方式
# 方式1,按照其格式来声明 >>> a={"key1" : 1, "key2" : "two"} >>> a {'key1': 1, 'key2': 'two'} # 方式2,使用dict函数 >>> a = dict(key1 = 1, key2 = "two") >>> a {'key1': 1, 'key2': 'two'}
-
修改添加键值对
>>> a['key1'] = 2 # 键值已存在,则修改键值 >>> a {'key1': 2, 'key2': 'two'} >>> a['key3'] = 1.2 >>> a {'key1': 2, 'key2': 'two', 'key3': 1.2} # 键值已存在,则增加键值对
-
BIF
>>> dir(dict) #使用dir函数查看内置操作 ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
-
访问字典
- keys() 返回键名
- values() 返回键值
- items() 返回键值对
>>> a.keys() dict_keys(['key1', 'key2', 'key3']) >>> a.values() dict_values([2, 'two', 1.2]) >>> a.items() dict_items([('key1', 2), ('key2', 'two'), ('key3', 1.2)])
-
get()
获取指定键名的键值,没有的话就没有返回值,也可以指定默认返回值
>>> a.get("key1") 2 >>> a.get("key5",0) 0 # 也可以使用 [] 来访问,若不存在则会报错 >>> a["key1"] 2
-
clear()
清空字典,不是删除。
>>> a.clear() >>> a
-
copy()
复制一个已有的字典
>>> b = a.copy() >>> b {'key1': 2, 'key2': 'two', 'key3': 1.2}
-
pop和popitem()
弹出键值和弹出项
>>> a.pop("key1") # 弹出指定键值,并返回值 2 >>> a {'key2': 'two', 'key3': 1.2} >>> a.popitem() # 弹出最后一个键值 ('key3', 1.2) >>> a {'key2': 'two'}
-
setdefault()
获取键名对应的值,若没有则添加一个键名,没有值,即None。
>>> a {'key2': 'two', 'key3': 1.2} >>> a.setdefault("key1") >>> a.setdefault("key3") 1.2 >>> a.setdefault("key4") >>> a {'key2': 'two', 'key3': 1.2, 'key1': None, 'key4': None}
-
update()
更新一个键对应的值。
>>> a.update(key4 = 4) # 注意键名是字符串也不用加引号,但值不行 >>> a {'key2': 'two', 'key3': 1.2, 'key1': None, 'key4': 4}
-
1.7 集合
list用了[]
tuple用了()
dic用了{}
集合与字典一样,使用{}
,但是其没有键值结构。示例
>>> a={1,2,3,4,5}
>>> type(a)
<class 'set'>
集合最大的特点是可以自动消去重复的元素,例如
>>> a={1,2,3,4,3,2,1}
>>> a
{1, 2, 3, 4}
-
初始化
# 手动定义 >>> a={1,2,3,4,5} >>> a {1, 2, 3, 4, 5} # 将列表和元组转换为set >>> list1=[1,2,3,4,3,2,1] >>> tuple1=(1,2,3,4,3,2,1) >>> a=set(list1) >>> a {1, 2, 3, 4} # 并且自动排序 >>> a=set(tuple1) >>> a {1, 2, 3, 4}
-
in & not in
判断是否存在元素
>>> a {1, 2, 3, 4} >>> 1 in a True >>> 5 not in a True
-
访问元素
# 集合没有顺序,不可以使用下表来访问,可以使用迭代器挨个输出 >>> for each in a: ... print(each, end=" ") ... 1 2 3 4
-
add() & remove()
分别可以添加元素和删除元素
>>> a {1, 2, 3, 4} >>> a.add("wuyao") >>> a {1, 2, 3, 4, 'wuyao'} >>> a.remove(1) >>> a {2, 3, 4, 'wuyao'}