1. 序列简介
序列指的是包含多项按序排列的数据的数据结构。
Python常见序列包括字符串、列表和元组。序列可通过索引访问操作。
元组和字符串相似不可修改。列表可以被修改。
my_list = ['python', 20]
my_tuple = ('python', 20)
2. 列表元组的通用用法
1)索引引用元素
索引从0开始,依次类推。倒数第一个索引为-1,倒数第二个为-2,依次类推。
2)子序列
[start: end: step]
a_tuple = ('crazyit', 20, 5.6, 'fkit', -17)
a_tuple[1:3] # (20, 5.6)
a_tuple[-3:-1] #(5.6, 'fkit')
b_tuple =(1, 2, 3, 4, 5, 6, 7, 8, 9)
b_tuple[2:8:2] #(3,5,7)
3) 加法
列表元组支持加法运算,和为所包含元素的总和。
元组只能加元组;列表只能加列表。
a_tuple = (1,2)
b_tuple = (3,4)
a_tuple + b_tuple #(1,2,3,4)
a_list = [1,2]
b_list = [3,4]
a_list + b_list #[1,2,3,4]
4) 乘法
a_tuple = (1,2)
a_tuple * 3 # (1,2,1,2,1,2)
a_list = [1,2]
a_list * 3 # [1,2,1,2,1,2]
加减法混用
order_endings = ('st', 'nd', 'rd')\
+ ('th',) * 17 + ('st', 'nd', 'rd')\
+ ('th',) * 7 + ('st',)
注意:(‘st’)就是字符串 ‘st’; (‘st’,)为元组
5) in运算符
a_tuple = (1,2)
1 in a_tuple # Ture
1 not in a_tuple # False
6) 长度、最大值、最小值
len()
max(), min(): 要求列表或元组的元素是相同类型且可以比较大小。
a_tuple = (20, 10, -2, 15.2, 102, 50)
max(a_tuple) # 102
min(a_tuple) # -2
len(a_tuple) # 6
7) 序列封包和序列解包
vals = 10, 20, 30
print(vals) # (10, 20, 30)
a,b,c = vals
print(a, b, c) # 10 20 30
a, b, c = 10, 20, 30
first, second, *rest = range(10)
print(first) # 0
print(rest) # [2, 3, 4, 5, 6, 7, 8, 9]
*begain, last = range(10)
print(begain) # [0, 1, 2, 3, 4, 5, 6, 7, 8]
print(last) # 9
first, *middle, last = range(10)
3. 使用列表
1) 创建列表
a_list = [1, 2]
a_list = list(range(1,5)) # [1, 2, 3, 4]
a_tuple = (1,2,3)
a_list = list(a_tuple) # [1, 2, 3]
a_list = [1, 2, 3]
a_tuple = tuple(a_list)
b_tuple = tuple(range(1, 5))
2) 增加列表元素
append:
将参数整体作为列表的一个元素添加到列表。
extend:
将参数中的各个元素作为列表的元素添加到列表。
a_list = [1, 2]
a_list.append(3) #[1, 2, 3]
a_list.append((4, 5)) # [1, 2, 3, (4, 5)]
a_list.append([6,7]) # [1, 2, 3, (4, 5), [6, 7]]
b_list = [1, 2]
b_list.extend((3, 4)) # [1, 2, 3, 4]
b_list.extend([5, 6]) # [1, 2, 3, 4, 5, 6]
c_list = [1, 2, 3, 4, 5]
c_list.insert(3, 'abc') #[1, 2, 3, 'abc', 4, 5]
c_list.insert(3, tuple('abc')) #[1, 2, 3, 'a', 'b', 'c', 'abc', 4, 5]
3) 删除列表元素
- del:可以删除列表的单一元素或一段元素;也可以删除变量。
- remove: 该方法不是根据索引删除元素, 而是根据元素本身进行删除,只删除第一个找到的元素,如果找不到引发ValueError错误。
- clear:清空列表所有元素。
a_list = [1, 2, 3, 4, 5] del a_list[3] # [1, 2, 3, 5] b_list = [1, 2, 3, 4, 5] del b_list[1:3] # [1, 4, 5] c_list = list(range(1, 10)) del c_list[2: -2: 2] # [1, 2, 4, 6, 8, 9] d_list = [1, 2, 3, 2, 4] d_list.remove(2) # [1, 3, 2, 4] e_list = [1, 2] e_list.clear() # []
4) 修改列表元素
- 通过索引赋值修改元素
- 通过slice语法对列表其中一部分赋值
a_list = [2, 4, -3.4, 'crazyit', 23] a_list[2] = 'fkit' print(a_list) # [2, 4, 'fkit', 'crazyit', 23] a_list[-2] = 9527 print(a_list) # [2, 4, 'fkit', 9527, 23] #通过slice语法对列表其中一部分赋值 b_list = list(range(1, 5)) print(b_list) # [1, 2, 3, 4] b_list[1:3] = ['a', 'b'] print(b_list) # [1, 'a', 'b', 4] b_list[2:2] = ['x', 'y'] #insert element print(b_list) # [1, 'a', 'x', 'y', 'b', 4] b_list[2 : 5] = [] print(b_list) # [1, 'a', 4] #通过slice语法赋值时,不能使用单个值;如果使用字符串赋值,则会当作序列出来,每个字符都是一个元素。 b_list[1:3] = 'Charlie' print(b_list) # [1, 'C', 'h', 'a', 'l', 'i', 'e'] c_list = list(range(1, 10)) c_list[2:9:2] = ['a', 'b', 'c', 'd'] print(c_list) # [1, 2, 'a', 4, 'b', 6, 'c', 8, 'd']
5) 列表的其他常用方法
- count(): 统计某个元素的出现次数。
a_list = [2, 30, 'a', [5, 30], 30] print(a_list.count(30)) # 2 print(a_list.count([5, 30])) #1
- index():定位某个元素在列表中的位置。
a_list = [2, 30, 'a', 'b', 'crazyit', 30] print(a_list.index(30)) # 1 #从索引2开始,定位30出现的位置。 print(a_list.index(30, 2)) # 5 #在索引2,4之间定位30的位置,注意不包括索引4的位置。 print(a_list.index(20, 2, 4)) # ValueError
- pop :出栈操作
stack = [] stack.append('fkit') stack.append('crazyit') stack.pop() # 'crazyit' stack.pot() # 'fkit'
- reverse():将列表中所有元素顺序反转。
- sort(): 对列表的所有元素进行排序。
4. 字典使用
1) 创建字典
key: 必需是不可变类型。
scores = {'语文':89, ‘数学’:92}
dict2 = {(20,30):'good', 30:'bad'}
vegetables = [('celery', 1.58), ('brocoli', 1.29)]
dict3 = dict(vegetables)
cars = [['BMW', 8.5], ['BENS', 8.3]]
dict4 = dict(cars)
dict5 = dict(spinach =1.39, cbbage = 2.59)
2) 字典基本操作
对不存在的key赋值,就是增加键值对。
使用del删除键值对。
对key运用in 或 not in 运算符。
3)字典常用方法
clear()
清空字典。
get()
根据key获取value,类似与使用方括号语法。用方括号访问不存在的key时,字典会引发Keyerror;get()用方括号访问不存在的key时,简单返回None,不会导致错误。
update()
更新已有或未有的键值对。
cars = {'BMW':8.5, 'BENS':8.3, 'AUDI':7.9}
cars.update({'BMW':4.5, 'PORSCHE':9.3})
print(cars) # {'BMW':4.5, 'BENS':8.3, 'AUDI':7.9, 'PORSCHE':9.3}
items() keys() values()
获取字典中的所有键值对、所有key、所有value
pop()
获取指定key对应的value,并删除这个key-value对
cars = {'BMW':8.5, 'BENS':8.3, 'AUDI':7.9}
cars.pop('AUDI') # 7.9
popitem()
随机弹出字典中的一个键值对。
setdefault()
根据key来获取对应的value的值。如果key存在,直接返回对应值;key不存在,先为key赋值为缺省值,在返回该值。
fromkeys()
使用给定的多个key创建字典,这些key对应的val默认都是None。
a_dict = dict.fromkeys(['a', 'b'])
print(a_dict) # {'a': None, 'b': None}
5. 使用字典格式化字符串
temp = '书名:%(name)s, 价格: %(price)010.2f'
book = {'name': 'Python', 'price': 88.9}
print(temp % book)