在Python中,最基本的数据结构是序列(Sequence),Python包含6中内建序列:列表、元组、字符串、Unicode字符串、buffer对象和xrange对象。
1. 通用序列操作
Python中所有序列都可以进行一些特定的操作:
- 索引(indexing)
- 分片(slicing)
- 序列相加(adding)
- 乘法(multiplying)
- 成员资格
- 长度
- 最小值
- 最大值
1.1 索引
序列中每个元素都分配一个数字,代表它在序列中的位置(索引),第一个索引是0,第二个索引是1,以此类推。
我们可以通过序列中元素编号对序列元素进行访问,如下例子
# 定义变量
greeting = 'Hello'
print(greeting[1])# 输出 e
序列从左往右,从0以此递增,也支持从右往左通过编号获取序列元素
# 从右往左读取元素
print(greeting[-1]) # 输出 o
print(greeting[-4]) # 输出 3
我们也可以不定义变量,直接对字符串进行索引操作
# 直接对字符串进行索引操作
print('Hello'[2]) # 输出 l
print('World'[-1])# 输出 d
1.2 分片
索引用来对单个元素的访问,使用分片可以获取一定范围的元素,分片通过冒号相隔的两个索引实现。
# 分片获取元素
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(numbers[1:3]) # [2, 3]
print(numbers[-3:-1]) # [8, 9]
print(numbers[:]) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
# 指定步长
print(numbers[0:10:1]) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(numbers[0:10:2]) # [1, 3, 5, 7, 9]
# print(numbers[::0]) ValueError: slice step cannot be zero
# 步长为负数
print(numbers[::-2]) # [0, 8, 6, 4, 2]
正步长,Python序列会从头部开始向右提取元素,负步长,序列会从尾部想左提取元素。
1.3 序列相加
使用加号进行序列相加操作。
# 序列相加
print([1, 2, 3, 4] + [5, 6, 7]) # [1, 2, 3, 4, 5, 6, 7]
s = 'Hello'
w = 'World'
print(s + w) # HelloWorld
# 数字 + 字符串
n = 1
print(s + n) # TypeError: can only concatenate str (not "int") to str
1.4 乘法
一个序列乘以一个数字N,原来序列内容重复N次,这就是序列的乘法。
print('=====================乘法=======================')
print('Hello' * 5) # HelloHelloHelloHelloHello
序列乘法通常可以做一些重复操作、空列表和None初始化操作。
1.5 成员资格
in运算符用于检查一个字符是否存在序列中。in运算符可运用于检验某个条件是否为真,并返回布尔值。这种运算又叫布尔运算符。
print('=====================成员资格=======================')
sw = 'Hello,World'
print('e' in sw) # true
print('w' in sw) # false
# print(1 in sw) TypeError: 'in <string>' requires string as left operand, not int
numbers = [1, 2, 3, 4, 5]
print(1 in numbers) # true
print(10 in numbers) # false
q = '123aaa'
# print(2 in q) TypeError: 'in <string>' requires string as left operand, not int
注意:数字类型不能在字符串中通过in运算符进行成员资格检验。
1.6 长度、最小值和最大值
长度:len
最小值:min
返回数据总最小成员
最大值:max
返回数据中最大成员
print('=====================长度、最小值和最大值=======================')
numbers = [100, 30, 900, 567, 332]
print(len(numbers)) # 5
print(min(numbers)) # 30
print(max(numbers)) # 900
2. 列表
-
列表就是队列
-
列表就是各种数据类型的集合,也是一种数据结构
-
列表是一种有序,且内容可重复的集合类型
2.1 列表的定义
- list 表示列表这种类型,可以用它定义一个列表
- 列表的元素存在于 [] 中
name = list(['小明', 'xiaoli', '王五'])
name_02 = ['小明', 'xiaoli', '王五']
注意:Python中列表是一个无限制长度数据结构,但是在使用中,尽量避免定义过长的列表。
列表常用运算符操作:
names = ('xiaoming', 'wangwu', 'xiaohong')
names_add = names + names
names_c = names * 10
print(names_add)
print(names_c)
print('names_c length is ', len(names_c))
names += ('abc', )
print(names)
names *= 10
print(names)
names_list = ['xiaoming', 'wangwu']
names_list += ['hehe']
print(names_list)
names_list *= 10
print(names_list)
print('xiaoming' in names_list)
print('xiaoming' not in names_list)
2.1 更新列表
列表除了统用序列的操作,还有自身独有的方法,如:
- 元素赋值
- 元素删除
- 分片赋值
- 列表方法
2.1.1 元素赋值
我们通过编号标记某个特定位置的元素,并对该位置的元素重新赋值。
print('=====================列表-元素赋值=======================')
a = [1, 2, 3, 7, 9]
a[0] = 3
print(a) # [3, 2, 3, 7, 9]
# 重新赋值-赋不同类型的值
a[1] = 'test'
print(a)
# 赋值的编号超过了列表中的最大编号
# a[16] = 1 IndexError: list assignment index out of range
注意:不能给列表不存在的编号赋值。
2.1.2 增加元素
列表初始化后,想要往这个列表中增加元素,可以使用 append() 方法。
append() : 用于在列表末尾添加新对象。
list.append(obj)
# list代表列表
# obj代表需要添加到list列表末尾的对象
b = [1, 2, 3, 4, 5]
b.append(5)
print(b) # [1, 2, 3, 4, 5, 5]
2.1.3 删除元素
想要删除列表中的元素,可以使用内置函数 del
# ------------删除元素-----------------
list_del = ['a', 'b', 'c', 'd', 'e']
print(len(list_del))
del list_del[1]
print('删除第二个元素后的列表:', list_del) # ['a', 'c', 'd', 'e']
num = [1, 2, 3, 4]
del num[2]
print(num) # [1, 2, 4]
2.1.4 分片赋值
分片赋值可对一定范围列表的元素进行操作。
str = list('女排夺冠了')
print(str)
show = list('hi,boy')
print(show)
show[3:] = list('man')
print(show)
如上**list 函数:**可以直接将字符串转换为列表
- 分片赋值可以替换与原序列长度不等的序列
greeting = list('hi')
print(greeting) # ['h', 'i']
greeting[1:] = list('ello')
print(greeting)
- 分片赋值可以不替换原有元素情况下,插入新元素
boil = list('女排夺冠了')
boil[2:2] = list('2016年奥运会')
print(boil) # ['女', '排', '2', '0', '1', '6', '年', '奥', '运', '会', '夺', '冠', '了']
- 分片赋值可以实现列表删除元素的操作
boil = list('女排2016年奥运会夺冠了')
print(boil)
boil[2:10] = []
print(boil) # ['女', '排', '夺', '冠', '了']
2.2 列表方法
2.2.1 append
- append() 用于在列表末尾添加新的元素
b = [1, 2, 3, 4, 5]
b.append(5)
print(b) # [1, 2, 3, 4, 5, 5]
- insert() 将一个元素添加到当前列表的指定位置
students = [
{'name': 'xiaoming', 'age': 33, 'id': 1, 'top': '174'},
{'name': '肖战', 'age': 10, 'id': 2, 'top': '175'}
]
xiaohong = {
'name': 'xiaohong',
'age': 18,
'sex': '女',
'id': 3,
'top': '160'
}
students.insert(0, xiaohong)
print(students)
xiaoqiang = {
'name': 'xiaoqiang',
'age': 18,
'sex': '男',
'id': 4,
'top': '188'
}
students.insert(3, None)
students.insert(4, None)
students.insert(5, None)
students.insert(6, xiaoqiang)
print(students)
xiaohuang = {
'name': 'xiaohuang',
'age': 18,
'sex': '男',
'id': 5,
'top': '178'
}
students.insert(3, xiaohuang)
print(students)
insert 和 append 的区别
- append 只能添加到列表的结尾,二insert可以选择任何一个位置
- 如果insert传入的位置列表中不存在,则将新元素添加到列表结尾
2.2.2 count
功能:
返回当前列表中某个成员的个数
用法:
inttype = list.count(item)
参数:
item:你想要查询个数的元素
注意事项:
- 如果查询的成员(元素)不存在,则返回0
- 列表只会检查完整元素是否存在需要计算的内容
animails = ['小猫', '小狗', '龙猫', '小猫', '鹦鹉', '小狗', '小兔子', '小猫']
cat = animails.count('小猫')
dog = animails.count('小狗')
l_cat = animails.count('龙猫')
rabbit = animails.count('小兔子')
print('我家的院子里有很多小动物')
print('其中小猫有 %s 只' % cat)
print('小狗有{}只'.format(dog))
print(f'龙猫有{l_cat} 只')
print('小兔子有 %d 只' % rabbit)
print('我们没有小松鼠,所以松鼠有 %s 只' % animails.count('松鼠'))
animails_dict = [
{'name': 'dog'},
{'name': 'dog'},
{'name': 'cat'}
]
dog_dict_count = animails_dict.count({"name": 'dog'})
print('小狗在动物的字典中有%s只' % dog_dict_count)
animails_tuple = ('小猫', '小狗', '龙猫', '小猫', '鹦鹉', '小狗', '小兔子', '小猫')
cat = animails_tuple.count('小猫')
dog = animails_tuple.count('小狗')
l_cat = animails_tuple.count('龙猫')
rabbit = animails_tuple.count('小兔子')
print('其中小猫 %s 有\n只小狗有 %s 只\n龙猫有 % s只\n小兔子有%s只' %(cat, dog, l_cat, rabbit))
2.2.3 remove
功能:
删除列表中的某个元素
用法:
list.remove(item)
参数:
item:准备删除的列表元素
remove的注意事项
- 如果删除的成员(元素)不存在,会直接报错
- 如果被删除的元素有多个,只会删除第一个
- remove函数不会返回一个新的列表,而是在原先的列表中对元素进行删除
Python的内置函数 del:
del把变量完全删除
shops = ['可乐', '洗发水', '可乐', '牛奶', '牛奶', '牙膏', '牙膏']
print('我们的超市有这些内容: %s' % shops)
print('我们的可乐有%s件产品' % shops.count('可乐'))
print('我们的洗发水有%s件产品' % shops.count('洗发水'))
print('我们的牛奶有%s件产品' % shops.count('牛奶'))
print('我们的牙膏有%s件产品' % shops.count('牙膏'))
print('我们要购买一件洗发水')
shops.remove('洗发水')
print('我们的洗发水还剩下%s件' % shops.count('洗发水'))
shops.remove('可乐')
print('当前可乐还有%s件' %shops.count('可乐'))
del shops
print(shops)
2.2.4 reverse
功能:
对当前列表顺序进行反转
用法:
list.reverse()
参数:
无参传递
students = [
{'name': 'xiaoming', 'age': 33, 'top': '174'},
{'name': 'xiaohong', 'age': 14, 'top': '175'},
{'name': 'xiaohuang', 'age': 18, 'top': '188'},
{'name': 'xiaoli', 'age': 18, 'top': '165'}
]
print('当前同学的顺序是{}'.format(students))
students.reverse()
print('更换之后的顺序是{}'.format(students))
2.2.5 sort
功能:
对当前列表按照一定规律进行排序
用法:
list.sort(key=None,reverse=False)
参数
key-参数比较
reverse--排序规则,reverse = True 降序,reverse = False升序(默认)
注意事项:
列表中的元素类型必须相同,否则无法排序(报错)
shu = '01老鼠'
niu = '02牛'
hu = '03老虎'
tu = '04兔'
long = '05龙'
she = '06蛇'
ma = '07马'
yang = '08羊'
hou = '09猴'
ji = '10鸡'
gou = '11狗'
zhu = '12猪'
shengxiao = []
shengxiao.append(gou)
shengxiao.append(ji)
shengxiao.append(zhu)
shengxiao.append(she)
shengxiao.append(tu)
shengxiao.append(hou)
shengxiao.append(hu)
shengxiao.append(niu)
shengxiao.append(shu)
shengxiao.append(long)
shengxiao.append(ma)
shengxiao.append(yang)
print(shengxiao)
print(len(shengxiao))
shengxiao.sort()
print(shengxiao)
shengxiao.sort(reverse=True)
print(shengxiao)
2.2.6 clear
功能:
将当前列表中的数据清空
用法:
list.cleat()->该函数无参数,无返回值
mixs = ['python', 1, (1), {'name': 'xiao'}]
print(mixs, len(mixs))
mixs.clear()
print(mixs, len(mixs))
2.2.7 copy
功能:
将当前的列表赋值一份相同的列表,新列表与旧列表内容相同,但内存空间不同
用法:
list.copy -> 该函数无参,返回一个一模一样的列表
copy与2次赋值的区别
a = [1, 2, 3]
b = a
- 二次赋值的变量与原始变量享有相同的内存空间
- copy函数创建的新列表与原始列表不是一个内存空间,不同享数据变更
old_list = ['python', 'django', 'flask']
new_list = old_list
new_list.append('tornado')
print(new_list)
print(old_list)
print(id(new_list), id(old_list))
del new_list
print(old_list)
old_list_copy = ['python', 'django', 'flask']
new_list_copy = old_list_copy.copy()
print(old_list_copy, new_list_copy)
new_list_copy.append('tornado_copy')
print(old_list_copy, new_list_copy)
print(id(old_list_copy), id(new_list_copy))
2.2.8 extend
功能:
将其他列表或元组中的元素导入当前列表中
用法:
list.extend(iterable) ->
参数:
iterable 代表列表或元组,该函数无返回值
manhua = []
history = []
code = []
new_manhua = ['a', 'b', 'c']
new_history = ['中国历史', '日本历史', '韩国历史']
new_code = ('python', 'django', 'flask')
manhua.extend(new_manhua)
history.extend(new_history)
code.extend(new_code)
print(manhua, history, code)
history.extend(manhua)
del manhua
print(history)
test = []
test.extend('asdf')
print(test)
2.2.9 index
功能:
从列表中找出某个值第一个匹配项的索引位置
用法:
list.index(obj)
field = ['hello', 'world', 'python', 'is', 'funny']
print('hello的索引位置为:', field.index('hello'))
print('python的索引位置为:', field.index('python'))
2.2.10 insert
功能:
函数用于将指定对象插入列表的指定位置。
用法:
list.insert(index,obj)
# 参数
list 代表列表
index 代表对象obj要插入的索引位置
obj 代表要插入列表的对象
num = [1, 2, 3]
num.insert(2, '插入位置在2之后,3之前')
print(num) # [1, 2, '插入位置在2之后,3之前', 3]
2.2.11 pop
功能:
用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
用法:
list.pop(obj=list[-1])
list 代表列表
obj 为可选参数,代表要移除列表元素的索引值
field = ['hello', 'world', 'python', 'is', 'funny']
field.pop()
print('移除元素后的field:', field) # 移除元素后的field: ['hello', 'world', 'python', 'is']
field.pop(3)
print('移除元素后的field:', field) # 移除元素后的field: ['hello', 'world', 'python']
3. 元组
- 元组和列表一样,都是一种可以存储多种数据结构的队列
- 元组也是一个有序的,且元素可以重复的集合
3.1 元组的定义
- 在Python中,tuple代表元组数据类型,也可以用它定义一个原则
- 元组中的元素存于 () 小括号中
name = tuple(('小明', 'hhh'))
name_01 = ('小明', 'hhh')
name_02 = ('小明',)
- 元组是一个无限制长度的数据结构
3.2 列表和元组的区别
- 元组比列表占用资源更小
- 列表是可变的,元组是不可变的
3.3 tuple函数
功能:
以一个序列作为参数,并把它转换为元组。如果参数是元组,参数就会原样返回。
# 参数为列表
print(tuple(['hello', 'world'])) # ('hello', 'world')
# 参数为元组
print(tuple(('hello', 'world'))) # ('hello', 'world')
3.4 元组的基本操作
- 访问元组
- 修改元组
- 删除元组
- 索引和截取
3.4.1 访问元组
可以使用下边索引访问元组中的值
mix = ('hello', 'world', 2015, 2016)
print('minx[1] is', mix[1])
num = (1, 2, 3, 4, 5, 6)
print('num[1:5] is :', num[1:5])
3.4.2 修改元组
元组的元素值不允许修改,但可以对元组进行连接组合
field = ('hello', 'world')
num = (2015, 2016)
print('合并结果为:', field+num) # 合并结果为: ('hello', 'world', 2015, 2016)
3.4.3 删除元组
元组中的元素值不允许删除,但可以使用del语句删除整个元组
field = ('hello', 'world')
del field