Python 数据类型进阶篇
整型int:通常被称为整型或整数,是正或负整数,不带小数点
定义:
var = 10 #本质var = int(10)
浮点型float:由整数部分与小数部分组成
定义:
var = 10.01 #本质var = float(10.01)
复数complex:由实数部分和虚数部分组成,
定义:
a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型
扩展知识-进制转换
#十进制转二进制:
>>> print(bin(10)) 0b1010
#十进制转八进制
>>> print(oct(10)) 0o12
#十进制转十六进制
>>> print(hex(10)) 0xa
二、字符串
Python 不支持单字符类型,单字符也在Python也是作为一个字符串使用
定义:
name = 'Yim' #还可以使用双引号和多引号
1、字符串内建函数
|
序号 |
方法及描述 |
|
1 |
capitalize() |
|
2 |
center(width, fillchar) |
|
3 |
count(str, beg= 0,end=len(string)) |
|
4 |
bytes.decode(encoding="utf-8", errors="strict") |
|
5 |
encode(encoding='UTF-8',errors='strict') |
|
6 |
endswith(suffix, beg=0, end=len(string)) |
|
7 |
expandtabs(tabsize=8) |
|
8 |
find(str, beg=0 end=len(string)) |
|
9 |
index(str, beg=0, end=len(string)) |
|
10 |
isalnum() |
|
11 |
isalpha() |
|
12 |
isdigit() |
|
13 |
islower() |
|
14 |
isnumeric() |
|
15 |
isspace() |
|
16 |
istitle() |
|
17 |
isupper() |
|
18 |
join(seq) |
|
19 |
len(string) |
|
20 |
ljust(width[, fillchar]) |
|
21 |
lower() |
|
22 |
lstrip() |
|
23 |
maketrans() |
|
24 |
max(str) |
|
25 |
min(str) |
|
26 |
replace(old, new [, max]) |
|
27 |
rfind(str, beg=0,end=len(string)) |
|
28 |
rindex( str, beg=0, end=len(string)) |
|
29 |
rjust(width,[, fillchar]) |
|
30 |
rstrip() |
|
31 |
split(str="", num=string.count(str)) |
|
32 |
splitlines([keepends]) |
|
33 |
startswith(str, beg=0,end=len(string)) |
|
34 |
strip([chars]) |
|
35 |
swapcase() |
|
36 |
title() |
|
37 |
translate(table, deletechars="") |
|
38 |
upper() |
|
39 |
zfill (width) |
|
40 |
isdecimal() |
2、 常用操作
#切片,取子字符串
>>> name = 'Yim'
>>> print(name[0:2])
Yi
>>> msg = 'My name is Yim'
>>> print(msg[0:7:2])
M ae
#strip,移除空白
>>> name = '*Yim*'
>>> print(name.lstrip('*')) #删除字符串左边的*号
Yim*
>>> print(name.rstrip('*')) #删除字符串右边的*号
*Yim
>>> print(name.strip('*')) #在字符串上执行 lstrip()和 rstrip()
Yim
#len, 返回字符串长度
>>> name = 'Yim'
>>> print(len(name))
3
#startswith,endswith,检查字符串是否以obj开始或结束
>>> name = 'Yim'
>>> print(name.startswith('Y')) #字符串是否以Y开始
True
>>> print(name.endswith('m')) #字符串是否以obj结束
True
#replace,将字符串中的str1替换成str2,,可以指定替换次数
>>> msg = 'My name is Yim'
>>> print(msg.replace('Yim','yim',1))
My name is yim
#format,字符串格式化
>>> res = '{} {} {}'.format('Yim','25','male')
>>> print(res)
Yim 25 male
>>> res = '{1} {0} {1}'.format('Yim','25','male')
>>> print(res)
25 Yim 25
>>> res = '{name} {age} {sex}'.format(sex='male',name='Yim',age=25)
>>> print(res)
Yim 25 male
#find,rfind,检测 str 是否包含在字符串中,可以指定范围(跟index差不多,区别是找不到不会报错)
>>> name = 'Yim'
>>> print(name.find('Y',0,1))
0
#count,检测str 在 string 里面出现的次数,可以指定范围
>>> name = 'Yim Yim Yim'
>>> print(name.count('Y',0,5))
2
# split,rsplit,以 str 为分隔符截取字符串,可以指定截取多少个字符串(默认分隔符为空格)
>>> passwd = 'root:x:0:0::/root:/bin/bash'
>>> print(passwd.split(':'))
['root', 'x', '0', '0', '', '/root', '/bin/bash']
>>> print(passwd.split(':',1))
['root', 'x:0:0::/root:/bin/bash']
>>> passwd = 'root:x:0:0::/root:/bin/bash'
>>> print(passwd.rsplit(':',1))
['root:x:0:0::/root', '/bin/bash']
#join,以指定字符串作为分割符,将所有的元素合并为一个新的字符串
>>> l = ['My','name','is','Yim']
>>> print(' '.join(l))
My name is Yim
#center,返回一个指定的宽度 width 居中的字符串
>>> name = 'Yim'
>>> print(name.center(30,'-'))
-------------Yim--------------
#ljust,rjust,返回一个原字符串左对齐或右对齐
>>> name = 'Yim'
>>> print(name.ljust(30,'-'))
Yim---------------------------
>>> print(name.rjust(30,'-'))
---------------------------Yim
#zfill,原字符串右对齐,前面填充0
>>> name = 'Yim'
>>> print(name.zfill(30))
000000000000000000000000000Yim
#expandtabs,把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8
>>> res = 'My\tname is Yim'
>>> print(res)
My name is Yim
>>> print(res.expandtabs(1))
My name is Yim
#lower,uppe,转换字符串中所有大写字符为小写和小写字符转大写
>>> name = 'Yim'
>>> print(name.lower())
yim
>>> print(name.upper())
YIM
#captalize,swapcase,title
>>> name = 'yim'
>>> print(name.capitalize()) #首字母大写
Yim
>>> print(name.swapcase()) #大小写翻转
YIM
>>> print(name.title()) #每个单词的首字母大写
Yim
#isdigit, 如果字符串只包含数字则返回 True 否则返回 False
>>> num = '1'
>>> print(num.isdigit())
True
#isdecimal, 检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false
>>> num = '1'
>>> print(num.isdecimal())
True
#isnumeric, 如果字符串中只包含数字字符,则返回 True,否则返回 False
>>> num = '1a'
>>> print(num.isnumeric())
False
#isalnum, 如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
>>> num = '1a'
>>> print(num.isalnum())
True
#isalpha, 如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False
>>> num = 'a'
>>> print(num.isalpha())
True
三、 列表
列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现
列表的数据项不需要具有相同的类型。与字符串的索引一样,列表索引从0开始
定义:
list = [1, 2, 3, 4, 5 ]
1、列表函数&方法
Python包含以下函数:
|
序号 |
函数 |
|
1 |
len(list) |
|
2 |
max(list) |
|
3 |
min(list) |
|
4 |
list(seq) |
Python包含以下方法:
|
序号 |
方法 |
|
1 |
list.append(obj) |
|
2 |
list.count(obj) |
|
3 |
list.extend(seq) |
|
4 |
list.index(obj) |
|
5 |
list.insert(index, obj) |
|
6 |
list.pop(obj=list[-1]) |
|
7 |
list.remove(obj) |
|
8 |
list.reverse() |
|
9 |
list.sort([func]) |
|
10 |
list.clear() |
|
11 |
list.copy() |
2、常用操作
#索引 >>> list = [1,2,3,4,5] >>> print(list[1]) 2 #切片,得到子列表 >>> list = [1,2,3,4,5] >>> print(list[0:2]) [1, 2] #拼接 >>> list = [1,2,3,4,5] >>> tinylist = [6,7,8,9,10] >>> print(list + tinylist) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #修改 >>> list = [1,2,3,4,5] >>> list[0] = 11 >>> print(list) [11, 2, 3, 4, 5] # append,追加 >>> list = [1,2,3,4,5] >>> list.append(6) >>> print(list) [1, 2, 3, 4, 5, 6] #insert,插入 >>> list = [1,2,3,4,5] >>> list.insert(1,9) >>> print(list) [1, 9, 2, 3, 4, 5] #pop,remove,删除 >>> list = [1,2,3,4,5] >>> list.pop() #按照索引删除,默认是最后一个元素 5 >>> print(list) [1, 2, 3, 4] >>> list = [1,2,3,4,5] >>> list.remove(4) #按照值删除 >>> print(list) [1, 2, 3, 5] #len,长度 >>> list = [1,2,3,4,5] >>> print(list.__len__()) 5 >>> print(len(list)) #用法一样 5 #循环 >>> list = [1,2,3,4,5] >>> for i in list:print(i) ... 1 2 3 4 5 #in,包含 >>> list = [1,2,3,4,5] >>> print(2 in list) True #重复输出 >>> list = [1,2,3,4,5] >>> print(list * 2) #输出两次 [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] #清空列表 >>> list = [1,2,3,4,5] >>> list.clear() >>> print(list) [] #复制列表 >>> list = [1,2,3,4,5] >>> a = list.copy() >>> print(a) [1, 2, 3, 4, 5] #统计某个元素在列表中出现的次数 >>> list = [1,2,3,4,5,1,2,3] >>> print(list.count(2)) 2 #在列表末尾一次性追加另一个序列中的多个值 >>> list = [1,2,3,4,5] >>> list.extend([6,7,8,9,10]) >>> print(list) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #从列表中找出某个值第一个匹配项的索引位置 >>> list = [1,2,3,4,5] >>> print(list.index(1)) 0 #反向列表中元素 >>> list = [1,2,3,4,5] >>> list.reverse() >>> print(list) [5, 4, 3, 2, 1] #对原列表进行排序 >>> list = [5,4,3,1] >>> list.sort() >>> print(list) [1, 3, 4, 5]
四、 元组
Python 的元组与列表类似,不同之处在于元组的元素不能修改
元组使用小括号,列表使用方括号
定义:
tuple = (1,2,3,4,5)
1、元组内置函数
|
序号 |
方法及描述 |
|
1 |
len(tuple) |
|
2 |
max(tuple) |
|
3 |
min(tuple) |
|
4 |
tuple(seq) |
2、 常用操作
#索引 >>> tuple = (1,2,3,4,5) >>> print(tuple[1]) 2 #切片 >>> tuple = (1,2,3,4,5) >>> print(tuple[0:2]) (1, 2) #循环 >>> tuple = (1,2,3,4,5) >>> for i in tuple:print(i) ... 1 2 3 4 5 #长度 >>> tuple = (1,2,3,4,5) >>> print(tuple.__len__()) 5 >>> print(len(tuple)) 5 #包含in >>> tuple = (1,2,3,4,5) >>> print(2 in tuple) True #拼接 >>> tuple = (1,2,3,4,5) >>> tinytuple = (6,7,8,9,10) >>> print(tuple + tinytuple) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) #重复输出 >>> tuple = (1,2,3,4,5) >>> print(tuple * 2) (1, 2, 3, 4, 5, 1, 2, 3, 4, 5) #统计某个元素在列表中出现的次数 >>> tuple = (1,2,3,4,5,1,2) >>> print(tuple.count(2)) 2
#从列表中找出某个值第一个匹配项的索引位置 >>> tuple = (1,2,3,4,5,1,2) >>> print(tuple.index(3)) 2
五、字典
字典是另一种可变容器模型,且可存储任意类型对象,字典是无序的
键必须是不可变和唯一的,但值则不必
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中
定义:
a = {'name':'Yim','age':25,'gender':'male'} #传统的文字表达方式
或:b = dict(name = 'Yim', age = 25, gender = 'male') #字典键值表
或:c = {}
c['name'] = 'Yim' #动态分配键值
或:d = dict([('name','Yim'),('age',25),('gender','male')]) #字典键值元组表
或:e = dict.fromkeys(['height','weight'],'normal') #所有键的值都相同或者赋予初始值
1、字典内置函数&方法
Python字典包含了以下内置函数:
|
序号 |
函数及描述 |
|
1 |
len(dict) |
|
2 |
str(dict) |
|
3 |
type(variable) |
Python字典包含了以下内置方法:
|
序号 |
函数及描述 |
|
1 |
radiansdict.clear() |
|
2 |
radiansdict.copy() |
|
3 |
radiansdict.fromkeys() |
|
4 |
radiansdict.get(key, default=None) |
|
5 |
key in dict |
|
6 |
radiansdict.items() |
|
7 |
radiansdict.keys() |
|
8 |
radiansdict.setdefault(key, default=None) |
|
9 |
radiansdict.update(dict2) |
|
10 |
radiansdict.values() |
|
11 |
pop(key[,default]) |
|
12 |
popitem() |
2、常见操作
#访问字典里的值
>>> dict = {'a':1,'b':2}
>>> print(dict['a'])
1
#增加
>>> dict = {'a':1,'b':2}
>>> dict['c'] = 3
>>> print(dict)
{'a': 1, 'b': 2, 'c': 3}
#pop,删除字典给定键 key 所对应的值,返回值为被删除的值
>>> dict = {'a':1,'b':2}
>>> dict.pop('a')
1
>>> print(dict)
{'b': 2}
>>> dict = {'a':1,'b':2}
>>> print(dict.pop('c',None)) #不会报错
None
#get,返回指定键的值
>>> dict = {'a':1,'b':2}
>>> print(dict.get('a'))
1
>>> dict = {'a':1,'b':2}
>>> print(dict.get('c',None)) #不会报错
None
#items,以列表返回可遍历的(键, 值) 元组数组
>>> dict = {'a':1,'b':2}
>>> print(dict.items())
dict_items([('a', 1), ('b', 2)])
#clear,删除字典内所有元素
>>> dict = {'a':1,'b':2}
>>> dict.clear()
>>> print(dict)
{}
#popitem,随机返回并删除字典中的一对键和值
>>> dict = {'a':1,'b':2}
>>> dict.popitem()
('b', 2)
>>> print(dict)
{'a': 1}
#keys,以列表返回字典中的所有键
>>> dict = {'a':1,'b':2}
>>> print(dict.keys())
dict_keys(['a', 'b'])
# values,以列表返回字典中的所有值
>>> dict = {'a':1,'b':2}
>>> print(dict.values())
dict_values([1, 2])
#copy,返回一个字典的浅复制
>>> dict = {'a':1,'b':2}
>>> a = dict.copy()
>>> print(a)
{'a': 1, 'b': 2}
#fromkeys,创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
>>> dict = dict.fromkeys(['a','b'],1)
>>> print(dict)
{'a': 1, 'b': 1}
#update,更新
>>> dict = {'a':1,'b':2}
>>> a = {'c':3,'d':4}
>>> dict.update(a) #键不存在则添加
>>> print(dict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> dict = {'a':1,'b':2}
>>> a = {'a':3,'b':4}
>>> dict.update(a) #键存在则更新
>>> print(dict)
{'a': 3, 'b': 4}
#len,计算字典元素个数,即键的总数
>>> dict = {'a':1,'b':2}
>>> print(len(dict))
2
#循环
>>> dict = {'a':1,'b':2}
>>> for key,item in dict.items():print(key,item)
...
a 1
b 2
#in,如果键在字典dict里返回true,否则返回false
>>> dict = {'a':1,'b':2}
>>> print('a' in dict)
True
六、集合
集合(set)是一个无序不重复元素的序列
基本功能是进行成员关系测试和删除重复元素
注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典
定义:
set = {'a','b','c','d'}
1、集合内置函数和操作符
Python包含以下内置函数:
|
序号 |
方法名称 |
操作 |
备注 |
|
1 |
s.issubset(t) |
如果s是t的子集,则返回True,否则返回False |
子集 < <= |
|
2 |
s.issuperset(t) |
如果s是t的超集,则返回True,否则返回False |
父集 > >= |
|
3 |
s.union(t) |
返回一个新集合,该集合是s和t的并集 |
并集 | |
|
4 |
s.intersection(t) |
返回一个新集合,该集合是s和t的交集 |
交集 & |
|
5 |
s.difference(t) |
返回一个新集合,该集合是s的成员,但不是t的成员 |
差集 - |
|
6 |
s.symmetric_difference(t) |
返回一个新集合,该集合是s或t的成员,但不是s和t共有的成员 |
对称差集 ^ |
|
7 |
s.copy() |
返回一个新集合,它是集合s的浅复制 |
|
集合操作符:

2、常见操作
#去重
>>> set = {'a','b',1,1,2,2}
>>> print(set)
{1, 2, 'a', 'b'}
#in,如果键在字典dict里返回true,可用作条件判断
>>> set = {'a','b','c','d'}
>>> print('a' in set)
True
#not in
>>> set = {'a','b','c','d'}
>>> print('a' not in set)
False
#|,并集
>>> set1 = {'a','b','c','d'}
>>> set2 = {'c','d','e','f'}
>>> print(set1 | set2)
{'c', 'a', 'd', 'f', 'b', 'e'}
#&,交集
>>> set1 = {'a','b','c','d'}
>>> set2 = {'c','d','e','f'}
>>> print(set1 & set2)
{'c', 'd'}
#-,差集
>>> set1 = {'a','b','c','d'}
>>> set2 = {'c','d','e','f'}
>>> print(set1 - set2)
{'a', 'b'}
#^,对称差集,不同时存在的元素
>>> set1 = {'a','b','c','d'}
>>> set2 = {'c','d','e','f'}
>>> print(set1 ^ set2)
{'e', 'a', 'b', 'f'}
#==,判断是否相等
>>> set1 = {'a','b','c','d'}
>>> set2 = {'a','b','c','d'}
>>> print(set1 == set2)
True
#!=
>>> set1 = {'a','b','c','d'}
>>> set2 = {'c','d','e','f'}
>>> print(set1 != set2)
True
#len,长度
>>> set = {'a','b','c','d'}
>>> len(set)
4
#>,>= ,<,<=父集,子集
>>> set1 = {'a','b','c','d'}
>>> set2 = {'a','b'}
>>> print(set1 > set2)
True
>>> print(set1 >= set2)
True
>>> print(set1 < set2)
False
>>> print(set1 <= set2)
False
#pop,删除元素
>>> set = {'a','b','c','d'}
>>> set.pop()
'c'
>>> print(set)
{'d', 'a', 'b'}
#remove,也是删除
>>> set = {'a','b','c','d'}
>>> set.remove('a')
>>> print(set)
{'c', 'd', 'b'}

浙公网安备 33010602011771号