列表
简单数据类型
- 整型<class ‘int’>
- 浮点型<class ‘float’>
- 布尔型<class ‘bool’>
容器数据类型
- 列表<class ‘list’>
- 元组<class ‘tuple’>
- 字典<class ‘dict’>
- 集合<class ‘set’>
- 字符串<class ‘str’>
1.列表的定义
列表是有序集合,没有固定大小,能够保存任意数量任意类型的 Python 对象,语法为 [元素1, 元素2, ..., 元素n]
。
2. 列表的创建
- 创建一个普通列表
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(x, type(x))
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] <class 'list'>
- 利用
range()
创建列表
x = list(range(1, 11, 2))
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>
- 利用推导式创建列表
x = [0 for i in range(5)]
print(x, type(x))
# [0, 0, 0, 0, 0] <class 'list'>
x = [i for i in range(1, 10, 2)]
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>
- 创建一个4*3的二维数组
由于list的元素可以是任何对象,因此列表中所保存的是对象的指针。
x = [[0] * 3] * 4
print(x, type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
x[0][0] = 1
print(x, type(x))
# [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] <class 'list'>
a = [0] * 3
x = [a] * 4
print(x, type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
x[0][0] = 1
print(x, type(x))
# [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] <class 'list'>
x = [a] * 4
操作中,只是创建4个指向list的引用,所以一旦a
改变,x
中4个a
也会随之改变。
- 创建一个混合列表
mix = [1, 'lsgo', 3.14, [1, 2, 3]]
print(mix, type(mix))
# [1, 'lsgo', 3.14, [1, 2, 3]] <class 'list'>
- 创建一个空列表
empty = []
print(empty, type(empty)) # [] <class 'list'>
列表内容可更改 (mutable),因此附加 (append
, extend
)、插入 (insert
)、删除 (remove
, pop
) 这些操作都可以用在它身上。
3.向列表中添加元素
list.append(obj)
在列表末尾添加新的对象,只接受一个参数,参数可以是任何数据类型,被追加的元素在list中保持着原结构类型。
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.append('Thursday')
print(x)
print(len(x))
#['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Thursday']
#6
append()
和extend()
的区别:
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.append(['Thursday', 'Sunday'])
print(x)
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', ['Thursday', 'Sunday']]
print(len(x))
# 6
此元素如果是一个 list,那么这个 list 将作为一个整体进行追加,注意append()和extend()的区别。
list.append()
追加的[‘Thursday’, ‘Sunday’]视为一个元素
list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表),追加的[‘Thursday’, ‘Sunday’]视为两个元素
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.extend(['Thursday', 'Sunday'])
print(x)
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Thursday', 'Sunday']
print(len(x)) # 7
严格来说 append 是追加,把一个东西整体添加在列表后,而 extend 是扩展,把一个东西里的所有元素添加在列表后。
list.insert(index, obj)
在编号 index
位置插入obj
。
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.insert(2, 'Sunday')
print(x)
# ['Monday', 'Tuesday', 'Sunday', 'Wednesday', 'Thursday', 'Friday']
print(len(x)) # 6
4.删除列表中的元素
list.remove(obj)
移除列表中某个值的第一个匹配项
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.remove('Monday')
print(x) # ['Tuesday', 'Wednesday', 'Thursday', 'Friday']
list.pop([index=-1])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
y = x.pop(0)
print(y) # Monday
y = x.pop(-2)
print(y) # Wednesday
print(x) # ['Tuesday', 'Thursday']
remove
和 pop
都可以删除元素,前者是指定具体要删除的元素,后者是指定一个索引。
del list[var2, ……]
删除单个或多个对象。
如果知道要删除的元素在列表中的位置,可使用del语句。
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
del x[0:2]
print(x) # ['Wednesday', 'Thursday', 'Friday']
5.获取列表中的元素
通过元素的索引值,从列表获取单个元素,注意,列表索引值是从0开始的。通过将索引指定为-1,可让Python返回最后一个列表元素,索引 -2 返回倒数第二个列表元素,以此类推。
x = ['Monday', 'Tuesday', 'Wednesday', ['Thursday', 'Friday']]
print(x[0], type(x[0])) # Monday <class 'str'>
print(x[-1], type(x[-1])) # ['Thursday', 'Friday'] <class 'list'>
print(x[-2], type(x[-2])) # Wednesday <class 'str'>
切片的通用写法是start : stop : step
x = ['Monday', 'Tuesday', 'Wednesday', ['Thursday', 'Friday']]
print(x[0], type(x[0])) # Monday <class 'str'>
print(x[-1], type(x[-1])) # ['Thursday', 'Friday'] <class 'list'>
print(x[-2], type(x[-2])) # Wednesday <class 'str'>
不进行设置时step
默认为1
- 情况 1 -
start:
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(x[3:]) # ['Thursday', 'Friday']
print(x[-3:]) # ['Wednesday', 'Thursday', 'Friday']
#左闭右开
- 情况 2 -
: stop
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[:3]) # ['Monday', 'Tuesday', 'Wednesday']
print(week[:-3]) # ['Monday', 'Tuesday']
- 情况 3 -
start : stop
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[1:3]) # ['Tuesday', 'Wednesday']
print(week[-3:-1]) # ['Wednesday', 'Thursday']
- 情况 4 -
start : stop : step
以具体的 step 从编号 start 往编号 stop 切片。注意最后把 step 设为 -1,相当于将列表反向排列。
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[1:4:2]) # ['Tuesday', 'Thursday']
print(week[:4:2]) # ['Monday', 'Wednesday']
print(week[1::2]) # ['Tuesday', 'Thursday']
print(week[::-1])
# ['Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday']
- 情况 5 -
:
复制列表中的所有元素(浅拷贝)。
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[:])
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
6.列表的常用操作符
等号操作符:==
连接操作符:+
重复操作符:*
成员关系操作符:in
, not in
列表拼接有两种方式,用+
和 *
,前者首尾拼接,后者复制拼接
list1 = [123, 456]
list2 = [456, 123]
list3 = [123, 456]
print(list1 == list2) # False
print(list1 == list3) # True
list4 = list1 + list2 # extend()
print(list4) # [123, 456, 456, 123]
list5 = list3 * 3
print(list5) # [123, 456, 123, 456, 123, 456]
list3 *= 3
print(list3) # [123, 456, 123, 456, 123, 456]
print(123 in list3) # True
print(456 not in list3) # False
前面三种方法(append
, extend
, insert
)可对列表增加元素,它们没有返回值,是直接修改了原数据对象。
而将两个list相加,需要创建新的 list 对象,从而需要消耗额外的内存,特别是当 list 较大时,尽量不要使用 “+” 来添加list。
7.列表的其它方法
list.count(obj)
统计某个元素在列表中出现的次数
list1 = [123, 456] * 3
print(list1) # [123, 456, 123, 456, 123, 456]
num = list1.count(123)
print(num) # 3
list.index(x[ ,start[ , end]])
从列表中找出某个值第一个匹配项的索引位置
- x-- 查找的对象。
- start-- 可选,查找的起始位置。
- end-- 可选,查找的结束位置。
list.reverse()
反向列表中元素
x = [123, 456, 789]
x.reverse()
print(x) # [789, 456, 123]
list.sort(key=None, reverse=False)
对原列表进行排序
- key --主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
- reverse --排序规则,reverse=T 降序, reverse=F 升序(默认)
- 该方法没有返回值,但是会对列表的对象进行排序。
练习题
- 列表操作练习
列表list 内容如下
list = [2, 5, 6, 7, 8, 9, 2, 9, 9]
请写程序完成下列操作:
在列表的末尾增加元素15:
在列表的中间位置插入元素20:
将列表[2, 5, 6]合并到list中:
移除列表中索引为3的元素:
翻转列表里的所有元素:
对列表里的元素进行排序,从小到大一次,从大到小一次:
- 修改列表
问题描述:
list = [1, [4, 6], True]
请将列表里所有数字修改成原来的两倍
元组
「元组」定义语法为:(元素1, 元素2, …, 元素n)
小括号把所有元素绑在一起
逗号将每个元素一一分开
1.创建和访问一个元组
- Python的元组与列表类似,不同之处在于tuple被创建后就不能对其进行修改,类似于字符串
- 元组使用小括号,列表使用方括号
- 元组与列表类似,也用整数来对它进行索引(indexing)和切片(slicing)
t1 = (1, 10.31, 'python')
t2 = 1, 10.31, 'python'
print(t1, type(t1))
# (1, 10.31, 'python') <class 'tuple'>
print(t2, type(t2))
# (1, 10.31, 'python') <class 'tuple'>
tuple1 = (1, 2, 3, 4, 5, 6, 7, 8)
print(tuple1[1]) # 2
print(tuple1[5:]) # (6, 7, 8)
print(tuple1[:5]) # (1, 2, 3, 4, 5)
tuple2 = tuple1[:]
print(tuple2) # (1, 2, 3, 4, 5, 6, 7, 8)
- 创建元组可以用小括号 (),也可以什么都不用,为了可读性,建议还是用 ()。
- 元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用。
x = (1)
print(type(x)) # <class 'int'>
x = (1,)
print(type(x)) # <class 'tuple'>
#元素不加逗号时,x为int。元素加逗号之后,x为tuple。
print(8 * (8)) # 64
print(8 * (8,)) # (8, 8, 8, 8, 8, 8, 8, 8) #复制8次 *重复操作符
创建二维元组
x = (1, 10.31, 'python'), ('data', 11)
print(x)
# ((1, 10.31, 'python'), ('data', 11))
print(x[0])
# (1, 10.31, 'python')
print(x[0][0], x[0][1], x[0][2])
# 1 10.31 python
print(x[0][0:2])
# (1, 10.31)
2.更新和删除一个元组
week = ('Monday', 'Tuesday', 'Thursday', 'Friday')
week = week[:2] + ('Wednesday',) + week[2:] #元组用+在相应位置添加元素,列表可以用insert添加.逗号是必须的,小括号也是必须的!
print(week) # ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')
元组有不可更改 (immutable) 的性质,因此不能直接给元组的元素赋值,但是只要元组中的元素可更改 (mutable),那么我们可以直接更改其元素,注意这跟赋值其元素不同。
t1 = (1, 2, 3, [4, 5, 6])
print(t1) # (1, 2, 3, [4, 5, 6])
t1[3][0] = 9
print(t1) # (1, 2, 3, [9, 5, 6])
3.元组相关的操作符
等号操作符:==
连接操作符:+
重复操作符:*
成员关系操作符:in、not in
元组拼接有两种方式,用「加号 +」和「乘号 *」,前者首尾拼接,后者复制拼接。同列表.
t1 = (123, 456)
t2 = (456, 123)
t3 = (123, 456)
print(t1 == t2) # False
print(t1 == t3) # True
t4 = t1 + t2
print(t4) # (123, 456, 456, 123)
t5 = t3 * 3
print(t5) # (123, 456, 123, 456, 123, 456)
t3 *= 3
print(t3) # (123, 456, 123, 456, 123, 456)
print(123 in t3) # True
print(456 not in t3) # False
4.内置方法
元组大小和内容都不可更改,因此只有 count 和 index 两种方法。
t = (1, 10.31, 'python')
print(t.count('python')) # 1
print(t.index(10.31)) # 1
- count(‘python’) 是记录在元组 t 中该元素出现几次,显然是 1 次
- index(10.31) 是找到该元素在元组 t 的索引,显然是 1
5.解压元组
解压(unpack)一维元组(有几个元素左边括号定义几个变量)
t = (1, 10.31, 'python')
(a, b, c) = t
print(a, b, c)
# 1 10.31 python
解压二维元组(按照元组里的元组结构来定义变量)
t = (1, 10.31, ('OK', 'python'))
(a, b, (c, d)) = t
print(a, b, c, d)
# 1 10.31 OK python
如果你只想要元组其中几个元素,用通配符「*」,英文叫 wildcard,在计算机语言中代表一个或多个元素。下例就是把多个元素丢给了 rest 变量。
t = 1, 2, 3, 4, 5
a, b, *rest, c = t
print(a, b, c) # 1 2 5
print(rest) # [3, 4]
如果你根本不在乎 rest 变量,那么就用通配符「*」加上下划线「_」。
t = 1, 2, 3, 4, 5
a, b, *_ = t
print(a, b) # 1 2
练习题
- 元组概念
写出下面代码的执行结果和最终结果的类型
(1, 2)*2
(1, )*2
(1)*2
- 拆包过程是什么?
对于可迭代对象,如元组、列表、字符串、集合、字典这些可迭代对象都可以被拆包,拆包是指将一个结构中的数据拆分为多个单独变量中。拆包的方式大致有两种,一种是以变量的方式来接收,另一种是用*
号。
以变量的方式接收一定要注意左右两边元素的个数和变量个数要统一,不然会报错。
第二种方式用*
来拆包
字符串
1.字符串的定义
- Python中字符串被定义为引号之间的字符集合.
- Python支持使用成对的 单引号 或 双引号
t1 = 'i love Python!'
print(t1, type(t1))
# i love Python! <class 'str'>
t2 = "I love Python!"
print(t2, type(t2))
# I love Python! <class 'str'>
print(5 + 8) # 13
print('5' + '8') # 58
Python的常用转义字符
如果字符串中需要出现单引号或双引号,可以使用转义符号\对字符串中的符号进行转义。
print('let\'s go') # let's go
print("let's go") # let's go
print('C:\\now') # C:\now
print("C:\\Program Files\\Intel\\Wifi\\Help")
# C:\Program Files\Intel\Wifi\Help
原始字符串只需要在字符串前边加一个英文字母 r 即可。
print(r'C:\Program Files\Intel\Wifi\Help')
# C:\Program Files\Intel\Wifi\Help
# r禁止转义
三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。
para_str = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
2.字符串的切片与拼接
- 类似于元组具有不可修改性
- 从0开始
- 切片通常写成
start:end
形式,左闭右开 - 索引值可正可负,正索引从0开始,从左往右;负索引从-1开始,从右往左.使用负数索引时,会从最后一个元素开始计数.最后一个元素的位置编号是-1.
str1 = 'I Love LsgoGroup'
print(str1[:6]) # I Love
print(str1[5]) # e
print(str1[:6] + " 插入的字符串 " + str1[6:])
# I Love 插入的字符串 LsgoGroup
s = 'Python'
print(s) # Python
print(s[2:4]) # th
print(s[-5:-2]) # yth
print(s[2]) # t
print(s[-1]) # n
3.字符串的常用内置方法
capitalize()
将字符串的第一个字符转换为大写
str2 = 'xiaoxie'
print(str2.capitalize()) # Xiaoxie
lower()
转换字符串中所有大写字符为小写
upper()
转换字符串中的小写字母为大写
swapcase()
将字符串中大写转换为小写,小写转换为大写
str2 = "DAXIExiaoxie"
print(str2.lower()) # daxiexiaoxie
print(str2.upper()) # DAXIEXIAOXIE
print(str2.swapcase()) # daxieXIAOXIE
string.count(str, start= 0, end = len(string))
返回str在string里面出现的次数,如果beg或者end指定则返回指定范围内str出现的次数.
start – 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
end – 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
str2 = "DAXIExiaoxie"
print(str2.count('xi')) # 2
endswith(suffix, beg = 0, end = len(string))
检查字符串是否以指定子字符串suffix结束,如果是,返回True.
startswith(substr, beg = 0, end = len(string))
检查字符串是否以指定字符串substr开头,如果是,返回True, 否则返回False.
str2 = "DAXIExiaoxie"
print(str2.endswith('ie')) # True
print(str2.endswith('xi')) # False
print(str2.startswith('Da')) # False
print(str2.startswith('DA')) # True
find(str, beg = 0, end = len(string))
检测str是否包含在字符串中, 如果指定范围beg和end,则检查是否包含在指定范围内,如果包含,返回开始的索引值,否则返回-1.
rfind(str. beg = 0, end = len(string))
类似find()函数,不过是从右边开始查找.
str2 = "DAXIExiaoxie"
print(str2.find('xi')) # 5
print(str2.find('ix')) # -1
print(str2.rfind('xi')) # 9
isnumeric()
如果字符串中只包含数字字符,则返回True,否则返回False.
str3 = '12345'
print(str3.isnumeric()) # True
str3 += 'a'
print(str3.isnumeric()) # False
ljust(width[, fillchar])
返回一个原字符串左对齐,并使用fillchar(默认空格)填充至长度width的新字符串.
rjust(width[, fillchar])
返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度width的新字符串
str4 = '1101'
print(str4.ljust(8, '0')) # 11010000
print(str4.rjust(8, '0')) # 00001101
- lstrip([chars]) 截掉字符串左边的空格或指定字符。
- rstrip([chars]) 删除字符串末尾的空格或指定字符。
- strip([chars]) 在字符串上执行lstrip()和rstrip()。
str5 = ' I Love LsgoGroup '
print(str5.lstrip()) # 'I Love LsgoGroup '
print(str5.lstrip().strip('I')) # ' Love LsgoGroup '
print(str5.rstrip()) # ' I Love LsgoGroup'
print(str5.strip()) # 'I Love LsgoGroup'
print(str5.strip().strip('p')) # 'I Love LsgoGrou'
partition(sub)
找到子字符串sub,把字符串分为一个三元组(pre_sub,sub,fol_sub),如果字符串中不包含sub则返回(‘原字符串’,’’,’’)。
rpartition(sub)
类似于partition()方法,不过是从右边开始查找。
str5 = ' I Love LsgoGroup '
print(str5.strip().partition('o')) # ('I L', 'o', 've LsgoGroup')
print(str5.strip().partition('m')) # ('I Love LsgoGroup', '', '')
print(str5.strip().rpartition('o')) # ('I Love LsgoGr', 'o', 'up')
replace(old, new [, max])
把 将字符串中的old替换成new,如果max指定,则替换不超过max次。
str5 = ' I Love LsgoGroup '
print(str5.strip().replace('I', 'We')) # We Love LsgoGroup
split(str="", num)
不带参数默认是以空格为分隔符切片字符串,如果num参数有设置,则仅分隔num个子字符串,返回切片后的子字符串拼接的列表。
str5 = ' I Love LsgoGroup '
print(str5.strip().split()) # ['I', 'Love', 'LsgoGroup']
print(str5.strip().split('o')) # ['I L', 've Lsg', 'Gr', 'up']
u = "www.baidu.com.cn"
# 使用默认分隔符
print(u.split()) # ['www.baidu.com.cn']
# 以"."为分隔符
print((u.split('.'))) # ['www', 'baidu', 'com', 'cn']
# 分割0次
print((u.split(".", 0))) # ['www.baidu.com.cn']
# 分割一次
print((u.split(".", 1))) # ['www', 'baidu.com.cn']
# 分割两次
print(u.split(".", 2)) # ['www', 'baidu', 'com.cn']
# 分割两次,并取序列为1的项
print((u.split(".", 2)[1])) # baidu
# 分割两次,并把分割后的三个部分保存到三个变量
u1, u2, u3 = u.split(".", 2)
print(u1) # www
print(u2) # baidu
print(u3) # com.cn
splitlines([keepends])
按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数keepends为 False,不包含换行符,如果为 True,则保留换行符。
str6 = 'I \n Love \n LsgoGroup'
print(str6.splitlines()) # ['I ', ' Love ', ' LsgoGroup']
print(str6.splitlines(True)) # ['I \n', ' Love \n', ' LsgoGroup']
maketrans(intab, outtab) 创建字符映射的转换表,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
translate(table, deletechars="") 根据参数table给出的表,转换字符串的字符,要过滤掉的字符放到deletechars参数中。
str7 = 'this is string example....wow!!!'
intab = 'aeiou'
outtab = '12345'
trantab = str7.maketrans(intab, outtab)
print(trantab) # {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}
print(str7.translate(trantab)) # th3s 3s str3ng 2x1mpl2....w4w!!!
4. 字符串格式化
format
格式化函数
str8 = "{0} Love {1}".format('I', 'Lsgogroup') # 位置参数
print(str8) # I Love Lsgogroup
str8 = "{a} Love {b}".format(a='I', b='Lsgogroup') # 关键字参数
print(str8) # I Love Lsgogroup
str8 = "{0} Love {b}".format('I', b='Lsgogroup') # 位置参数要在关键字参数之前
print(str8) # I Love Lsgogroup
str8 = '{0:.2f}{1}'.format(27.658, 'GB') # 保留小数点后两位
print(str8) # 27.66GB
Python字符串格式化符号:
- 格式化操作符辅助指令
练习题
- 字符串函数回顾
- 怎么批量替换字符串中的元素?
replace(old, new) - 怎么把字符串按照空格进行拆分?
split(str=“”),默认按照空格分隔 - 怎么去除字符串首位的空格?
lstrip()