数值、字符串和列表的基本操作举例
本节课的主要内容是数值、字符串和列表的基础操作,内容很零碎,把这些知识点统计起来,今后如果不小心忘记了某项操作,还能翻看日志查询。怪不得人们说python是一门语言,的确,我们在组词造句写文章之前必须知道每个单词的含义,这要记。但记住汉字或者英文单词只是学习语言的前提,语句的构造和输出是需要逻辑的,这个逻辑需要自己不断地学习,摸索和体会,学习某个具体操作并不是重点,学习到背后的逻辑支持才是关键,所以一定要会举一反三,触类旁通❤️。
1. 列表 list
* --------- ① 下标索引及长度测量
>>> l=[1,2,3,4]
>>> l
[1, 2, 3, 4]
>>> l[0] # 下标索引,且用中括号表示
1
>>> len(l) # 查询列表内对象的个数,用小括号
4
>>> l[0],len(l) # 出现有序数对
(1, 4)
注:可通过下标索引原位改变列表对象
* --------- ② 追加新列表以及append( )的应用
>>> l=[1,2,3,4]
>>> for i in l:
... print(i**2) # 与PHP都具有脚本源的特性
...
1
4
9
16
>>> res=[]
>>> for i in l:
... res.append(i**2) #将列表的部分内容以一定规则(自定义)追加到新列表中
...
>>> res
[1, 4, 9, 16]
>>> l1=[i**2 for i in l] # 更简便的新列表内容追加法
>>> l1
[1, 4, 9, 16]
>>> l1[2]=5 # 列表的可变序列特性
>>> l1
[1, 4, 5, 16]
>>> l1.append(31) # 列表后面直接追加
>>> l1
[1, 4, 5, 16, 31]
* --------- ③ 列表乘积‘*’的应用
>>> ['carla']*3
['carla', 'carla', 'carla'] # 仍然是一个list
>>> s=['carla']
>>> m=[s*3]
>>> m
[['carla', 'carla', 'carla']] # list中的list,类比于数学集合中有一个集合元素{{0,1,2}}
>>> m=s*3
>>> m
['carla', 'carla', 'carla']
>>> m=[c*3 for c in s]
>>> m
['carlacarlacarla']
补充:
如何理解:c*3 for c in s,
<1> 若s是一个列表:返回时以每个列表元素(非字符)为基础,✖️3次显示在同一个列表中,新列表中元素个数不变;
<2>若s是一个字符串:返回时以每个字符✖️3,多少个字符就会呈现多少个列表元素.
>>> s=['carla'] # s声明是list,包含1个元素
>>> m=[c*3 for c in s] # 返回1个元素
>>> m
['carlacarlacarla']
>>> s=['carla','classroom'] # s声明是list,包含2个元素
>>> m=[c*3 for c in s]
>>> m
['carlacarlacarla', 'classroomclassroomclassroom'] # 返回2个元素
>>> n='carla' # n声明是str,包含1个元素,5个字符
>>> m=[c*3 for c in n]
>>> m
['ccc', 'aaa', 'rrr', 'lll', 'aaa'] # 返回5个元素,每个元素是每个字符✖️3
>>> m=[c*3 for c in 'carla'] # 直接in 某一个str,效果一样
>>> m
['ccc', 'aaa', 'rrr', 'lll', 'aaa']
>>> n="carla's classroom"
>>> m=[c*3 for c in n]
>>> m
['ccc', 'aaa', 'rrr', 'lll', 'aaa', "'''", 'sss', ' ', 'ccc', 'lll', 'aaa', 'sss', 'sss', 'rrr', 'ooo', 'ooo', 'mmm']
* --------- ④ 列表的扩展extend( )
注意:append()只能追加一个元素,但extend()可以扩展列表,追加多个元素
>>> s=[1,2,3,4]
>>> s.extend([5,6,7,8]) # 增加4个元素
>>> s
[1, 2, 3, 4, 5, 6, 7, 8]
* --------- ⑤ 列表新元素的插入insert( )
names=['Lihua','Rain','Jack','Xiuxiu','Peiqi','Black']
names.insert(-1,'Blue') # 在最后一个位置前插入新元素‘Blue’
print (names)
names[names.index('Xiuxiu')]='秀秀'
print(names)
运行结果:
['Lihua', 'Rain', 'Jack', 'Xiuxiu', 'Peiqi', 'Blue', 'Black']
['Lihua', 'Rain', 'Jack', '秀秀', 'Peiqi', 'Blue', 'Black']
在最后位置插入一个新元素,还可以这样:
>>> names=['Lihua','Rain','Jack','Xiuxiu','Peiqi','Black']
>>> names[5:]='Blue',names[5]
>>> names
['Lihua', 'Rain', 'Jack', 'Xiuxiu', 'Peiqi', 'Blue', 'Black']
* --------- ⑥ 列表排序sort( )& reverse( )
>>> s=[7,4,3,8,5,6]
>>> s.sort()
>>> s
[3, 4, 5, 6, 7, 8] # 从小到大排序
>>> s.reverse() # 从大到小排序
>>> s
[8, 7, 6, 5, 4, 3]
>>> s=['carla','hello','nice','go']
>>> s.sort()
>>> s
['carla', 'go', 'hello', 'nice'] # 按首字母在字母表的顺序排列
>>> s.reverse()
>>> s
['nice', 'hello', 'go', 'carla']
* --------- ⑦ 列表的删除.pop()和全局删除delete()
<1> list.pop()
>>> s=['nice', 'hello', 'go', 'carla']
>>> s.pop()
'carla' # 在列表中弹出最后一个元素“carla”
>>> s
['nice', 'hello', 'go'] # 列表已更改
>>> s.pop() # 在列表中再弹出最后一个元素
'go'
>>> s
['nice', 'hello']
>>> m=[4,3,5,7,1] # 对于数值元素,道理一样
>>> m.pop()
1
>>> m
[4, 3, 5, 7]
>>> m.pop()
7
>>> m
[4, 3, 5]
注:这种方法类似于堆栈的方法
<2> 全局del()操作
>>> s=['carla', 'go', 'hello', 'nice']
>>> del(s[0]) # 删除list的第1个元素(可任意选择第几个元素)
>>> s
['go', 'hello', 'nice']
* --------- ⑧ 列表的查找索引 .index()和元素个数统计count()
>>> s=['carla', 'go', 'hello', 'nice','nice']
>>> s.index('go') # 查找“go”这个元素的下表索引
1
>>> s.count('nice') # 统计“nice”这个元素的个数
2
* --------- ⑨ 列表的引用与复制
注意
:引用类型也支持原位改变,所以引用要慎重!!
>>> s=[1,2,3,4]
>>> s=[1,2,3,4]
>>> carla=[1,2,3,4]
>>> david=carla # 直接赋值时新列表随着原列表的变化而变化
>>> carla[0]=5
>>> carla
[5, 2, 3, 4]
>>> david
[5, 2, 3, 4] # 新列表david随之变化
>>> david=carla[:]
>>> carla[1]=6
>>> carla
[5, 6, 3, 4]
>>> david
[5, 2, 3, 4] # 此时david ≠ carla
>>> a=[1,2,3]
>>> b=a[:] # 方式一:列表切片法,可切局部或者整体
>>> c=list(a) # 方式二:列表复制法
>>> d=a*1 # 方式三:列表*1法
>>> a
[1, 2, 3]
>>> b
[1, 2, 3]
>>> c
[1, 2, 3]
>>> d
[1, 2, 3]
>>> a[0]=4 # 改变原列表a的某一个元素
>>> a
[4, 2, 3]
>>> b
[1, 2, 3] # b,c,d 均不变
>>> c
[1, 2, 3]
>>> d
[1, 2, 3]
>>> import copy # 导入copy
>>> e=copy.copy(a) # 方式四: copy.copy()法
>>> e
[4, 2, 3]
>>> a[1]=5
>>> a
[4, 5, 3]
>>> e
[4, 2, 3]
>>> f=copy.deepcopy(a) # 方式五:copy.deepcopy()
>>> f
[4, 5, 3]
所以:<1> 列表切片法 <2> 列表复制法 <3> 列表*1法 <4> copy.copy()法 <5> copy.deepcopy()法
2. 字典表 dictionary
>>> d={"name":"carla","age":20,"job":"student"} # 字典的内容用花括号
>>> d["name"] #用中括号查询或调取数据
'carla'
>>> d.get('age')
20
>>> d.get('gender') # 这种方式不会报错,可以设置默认返回值
>>> d.get('gender','female')
'female'
3. 元组 tuple
>>> t=(1,2,3,4)
>>> t
(1, 2, 3, 4)
>>> l[3]
4
元组与列表的区别
>>> t=(1,2,3,4)
>>> l=[1,2,3,4]
>>> t[3] # 都可以使用下标索引查找
4
>>> l[3]
4
>>> l[3]='xyz' # 列表可以对局部位置进行修改
>>> l
[1, 2, 3, 'xyz']
>>> t[3]='abc'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment # 报错!
注:元组内位置不允许修改
4. 布尔:Boolean
* --------- ① 布尔(True & False)结果初应用
>>> score=62.5
>>> score>=60 # 比较返回布尔型结果
True
>>> score==60
False
>>> score!=60
True
>>> s='carla'
>>> 'l' in s # 判断某个或某几个字符是否在已知str中
True
>>> 'car'in s
True
>>> 'm' in s
False
* --------- ② 布尔(True & False)结果兼容性
>>> 3>1
True
>>> isinstance(True,int) # 检验类型是否兼容
True
>>> True==1
True
>>> False==0
True
>>> True+2 # 可参与int的运算
3
布尔型返回结果:True和False
比较类型:<,>,<=,>=,==,!=
**5. 数值型数据类型 -------- 声明通过赋值实现
* 数值显示
>>> '3+5*3={0}'.format(18) # 字符串中占位符的使用
'3+5*3=18'
>>> f=2.222222
>>> 'f={0}'.format(2*f) # format()仍可以对数值进行运算,再以字符串形式将结果显示出来
'f=4.444444'
>>> 'f={0:.2f}'.format(f) # 局部调整,占位符部分的数值是与f一样的浮点型,并且保留两位有效数字
'f=2.22'
. ps:
--------- 占位符在字典(dic)中的应用:
>>> d={'name':'carla','age':20,'job':'student'}
>>> '姓名:{0},年龄:{1}'.format(d.get('name'),d.get('age'))
'姓名:carla,年龄:20'
* 相除与取整
* --------- ① 除法取整
>>> 10/4 # 整数除法默认取整
2
>>> 10/4.0 # 按精度高的运算(不取整)
2.5
>>> 10//4 # 除法取整
2
>>> 10//4.0 # 按精度高的运算(取整)
2.0
* --------- ② math.floor()取整
>>> import math
>>> math.floor(4.5)
4.0
>>> math.floor(4.9)
4.0
>>> math.floor(-4.9)
-5.0
>>> math.floor(-4.49)
-5.0
注:
math.floor模块取整是以不大于这个数为依据。类似于高斯取整:
* --------- ③ math.trunc()取整
>>> math.trunc(4.35) # 靠近原点
4
>>> math.trunc(4.85)
4
>>> math.trunc(-4.35)
-4
>>> math.trunc(-4.85)
-4
math.trunc()取整原则:向原点靠近。
* --------- ④ round()取整 四舍五入取整
>>> round(3.14)
3
>>> round(3.84) # 满足常规习惯:四舍五入
4
>>> round(-3.14)
-3
>>> round(-3.84)
-4
* 数值的进制转换
规则 | 二进制 | 八进制 | 十六进制 |
---|---|---|---|
转入十进制 | 0b | 0o | 0x |
十进制转出 | bin( ) | oct( ) | hex( ) |
>>> 0o1
1
>>> 0b11 # 二进制转为十进制
3
>>> 0b110
6
>>> 0o71 # 八进制转为十进制
57
>>> 0x13
19
>>> 0x15 # 十六进制转为十进制
21
注:
其他进制转换为十进制的数学方法:
- 0b110–>22+21=6
- 0o71–>8*7+1=57
- 0x15–>16*1+5=21
>>> bin(31) # 十进制转二进制
'0b11111'
>>> oct(31) # 十进制转八进制
'0o37'
>>> hex(31) # 十进制转十六进制
'0x1f'
注:
十进制转换为其他进制的数学方法:
- bin(31)–>24+23+22+21+1–> 0b11111
- oct(31)–>8*3+7–> 0o37
- hex(31)–>16*1+15–> 0xf
- import decimal 提高精度
>>> import decimal
>>> decimal.Decimal('1.2')
Decimal('1.2')
>>> decimal.Decimal('1.2')+decimal.Decimal('3.4')
Decimal('4.6') # 导入decimal计算要比float精度高
>>> 1.2+3.4
4.6
>>> decimal.Decimal('1.1')+decimal.Decimal('2.2')
Decimal('3.3')
>>> 1.1+2.2
3.3000000000000003
6. 字符串
* --------- ① 转义
>>> word="what's your name?"
>>> word
>>> 'what\'s your name?' # 加入转义符
"what's your name?"
常见转义符: '\','\\','\n','\b','\t','\a'
>>> path='D:\桌面\new123.txt' # 路径选择
>>> path
'D:\\桌面\new123.txt'
>>> path='D:\\桌面\\new123.txt' # 可以用'\\'或者'\'表示
>>> path
'D:\\桌面\\new123.txt'
>>> path='D:\桌面\\new123.txt'
>>> path
'D:\\桌面\\new123.txt'
>>> path=r'D:\桌面\new123.txt' # 路径前面加'r',意为根root,不被转义影响了
>>> path
'D:\\桌面\\new123.txt'
注:忽略转义符,加‘r’
def avg()
...""""计算平均数"""
... pass
注:三引号注释与#井号注释的不同: 三引号注释不会被忽略掉,可生成说明性文档,后期可被调取
import math
help(math) # 调取math模块的说明
* --------- ② 字符串的输出方式
>>> print('abc')
abc
>>> print('ok')
ok
>>> print('ok'*5) # 简化步骤
okokokokok
>>> print('-'*5)
-----
>>> print('*'*5) # 简化步骤
*****
👆:乘积形式的批量输出
m = 'carla'
for s in m: # 在m中的单个字符,找到后打印出来
print(s) # 注意终端中要用到table(空四格键),打印以后默认都有终止符号"\n"
输出::
c
a
r
l
a
m = 'carla'
for s in m:
print(s,end="") # 找到单个字符以后,不要换行,以自定义方式输出
print('\n')
for n in m:
print(n,end="+")
输出:
carla
c+a+r+l+a+
👆👆:单个或多个字符的自定义输出
>>> m ='mathematical'
>>> m[0] # 第1个字符
'm'
>>> m[-1] # 最后1个字符
'l'
>>> m[len(m)-1]
'l'
>>> m[:] # 全部字符
'mathematical'
>>> m[0:3] # 第1个到第3个字符
'mat'
>>> m[::2] # 每隔1个字符
'mteaia'
>>> m[::-1] # 倒序全部字符
'lacitamehtam'
👆👆👆:以一定顺序的字符输出
注意:[0:3]不包含下标为3时对应的字符
,类似于数学集合左闭右开"[ , )".
* --------- ③ 字符串字符更改的实现
>>> s="carla'sclassroom.cm" # 不支持原位置改变
>>> s.replace('cm','cn')
"carla'sclassroom.cn"
>>> s
"carla'sclassroom.cm"
注:字符串不支持原位置改变,如s[0]=x, 报错!
我们可以借助列表来实现字符串字符的改变,因为列表是序列,支持原位字符改变。如下:
>>> l=list(s)
>>> l
['c', 'a', 'r', 'l', 'a', "'", 's', 'c', 'l', 'a', 's', 's', 'r', 'o', 'o', 'm', '.', 'c', 'm']
>>> l[-1]='n' # 最后一个位置字符更改为'n'
>>> l
['c', 'a', 'r', 'l', 'a', "'", 's', 'c', 'l', 'a', 's', 's', 'r', 'o', 'o', 'm', '.', 'c', 'n']
# 最后一个字符在列表原位改变
如果想要把修改好的字符重新赋值给字符串s,该如何操作呢?
>>> s=''.join(l) #join加入连接,‘’,空字符串,语句表示将l的各个元素中间以空字符串相连,再赋值给s
>>> s
"carla'sclassroom.cn"
>>> s='*'.join(l) #语句表示将l的各元素中间以“*”相连,再赋值给s
>>> s
"c*a*r*l*a*'*s*c*l*a*s*s*r*o*o*m*.*c*n" # 自定义输出样式
* --------- ④ 字符串的切割方法
如何使用split切割字符串
>>> w='baidu.com,sina.com,carla.com'
>>> w.split(',') # 以“,”为识别符,切割字符串
['baidu.com', 'sina.com', 'carla.com']
>>> l= w.split(',') # 用切割完的字符串建立一个新的列表
>>> l
['baidu.com', 'sina.com', 'carla.com']
-
-
- 注意:len()是全局里面定义好的,并不依附于某一个对象,而s.split()是一个方法,基于字符串的一个实例。python在定义字符串这个类的时候给我们写的一个方法,这个方法不是谁都可以用的。
从面向对象的角度来分析的话,s.split()称之为方法,len()称之为函数。
- 注意:len()是全局里面定义好的,并不依附于某一个对象,而s.split()是一个方法,基于字符串的一个实例。python在定义字符串这个类的时候给我们写的一个方法,这个方法不是谁都可以用的。
-
- --------- ⑤ 字符串的开头与结尾的判断方法——startswith,endswith
>>> x="carla'sclassroom.cn"
>>> x.startswith('abc')
False
>>> x.startswith('car')
True
>>> x.endswith('cm')
False
>>> x.endswith('cn')
True
* --------- ⑤ 字符串的开头与结尾的判断方法——find
>>> x="carla'sclassroom.cn"
>>> x.find('car') # 寻找“car”的位置
0 # 在第一个位置
>>> x.find('room')
12 # 在第十三个位置
>>> x.find('.')
16
>>> x.find("'") # 如果是寻找单引号,就用双引号标出,否在报错,如下↓
5
>>> x.find(''')
... # 无法输出,陷入死循环
...
* --------- ⑥ 字符串中的变量交换
… 方式一
>>> a,b=1,2
>>> a
1
>>> b
2
>>> a,b=b,a
… 方式二
>>> a,b=1,2
>>> b='{}'.format(a) # 导入占位符
>>> b
'1'
>>> b=int('{}'.format(a)) # integer类型
>>> b
1
总结
···鲁迅先生曾经说过:“时间就像海绵里的水,只要愿挤,总还是有的。” “我只是把别人喝咖啡的时间用在了工作上。”
那个小谁要加油哇!💪💪