Python数据类型 - 列表

2023-10-17 09:28:49 浏览数 (1)

介绍

列表是常见的基本数据类型,列表和字符串一样都是有序排列的,可以用切片和索引的方式访问数据,并且列表是可变数据类型

创建一个列表

info= ["name",''age","sex"]

本质上就是info = list(["name",''age","sex"])

直接将字符串转换为列表,list会把字符串用for循环迭代一下,然后将字符串的每一个值当做list的元素。

代码语言:javascript复制
>>> name = "python"
>>> li = list(name)
>>> li
['p', 'y', 't', 'h','o','n']

列表的基本操作有:索引(访问),切片,扩展,删除,追加,统计,长度,获取下标等。

1,访问,根据索引

代码语言:javascript复制
>>> info= ["name","age",,"sex","height"]
 >>> info[0]#访问列表中第一个元素
 'name' 
 >>> info[1]#访问列表中第二个元素
 'age' 
 >>> info[-1]#访问列表中最后一个元素
 'height'
 >>> info[-2]#访问列表中倒数第二个元素
 'sex'

2,切片

代码语言:javascript复制
>>> info= ["name","age","hobbies","sex",1,2,3,"height"]
>>> info[1:3]#取1到3之间的值,包括1不包括3,顾头不顾尾
['age', 'hobbies']
>>> info[1:-1]#取1到最后一个之间的值
['age', 'hobbies', 'sex', 1, 2, 3]
>>> info[0:3]#取第一个到第三个之间的值
['name', 'age', 'hobbies']
>>> info[:3]#效果同上,0可以省略掉
['name', 'age', 'hobbies']
>>> info[3:]#取3到最后的值
['sex', 1, 2, 3, 'height']
>>> info[1:8:2]#每隔2步取一个值,取1到8之间的值,这里的2是步长,当然也可以用3做步长,默认步长是1
['age', 'sex', 2, 'height']
>>>

3,追加,插入,扩展

代码语言:javascript复制
>>> info= ["name","age","hobbies","sex",1,2,3,"height"]
>>> info.append("girls")#append添加默认是末尾位置
>>> info
['name', 'age', 'hobbies', 'sex', 1, 2, 3, 'height', 'girls']
>>> info.insert(1,"apple")#insert可以根据索引在指定位置添加
>>> info
['name', 'apple', 'age', 'hobbies', 'sex', 1, 2, 3, 'height', 'girls']
>>> x =["lenovo","apple","mac"]
>>> info.extend(x)#extend用于在列表末尾一次性追加另一个序列中的多个值
>>> info
['name', 'apple', 'age', 'hobbies', 'sex', 1, 2,3, 'height', 'girls', 'lenovo', 'apple', 'mac']
>>>

4,修改

代码语言:javascript复制
>>> x =["lenovo","apple","mac"]
>>> x[0]="xiaomi"#通过下标直接修改
>>> x
['xiaomi', 'apple', 'mac']
>>>

5,删除

代码语言:javascript复制
>>> x =["xiaomi","apple","mac"]
>>> del x[1]#根据下标删除
>>> x
['xiaomi', 'mac']
 
>>> x.remove("mac")#指定元素删除
>>> x
['xiaomi']
 
>>> x =["xiaomi","apple","mac"]
>>> x.pop()#删除最后一个元素'mac'
>>> x =["xiaomi","apple","mac"]
>>> x.pop(0)#根据下标删除,有返回值'xiaomi'
>>> x =["xiaomi","apple","mac"]
>>> x.clear()#清除所有
>>> x
[]

6,统计     个数(count),长度(len)

代码语言:javascript复制
>>> x =["xiaomi","apple","mac","xiaomi","boys","girls"]
>>> x.count("xiaomi")#统计列表中“xiaomi”的个数
2
>>> x =["xiaomi","apple","mac","xiaomi","boys","girls"]
>>> len(x)#统计列表中元素的总长度(总个数)
6

7,排序&翻转

代码语言:javascript复制
>>> x =["lenovo","apple","mac","lenovo","boys","girls",23,"Alex","HUWEI"]
>>> x[-3]="23"#不是同类型不能排序,转换成str类型
>>> x.sort()#排序顺序数字>大写>小写
>>> x
['23', 'Alex', 'apple', 'boys', 'girls', 'lenovo', 'lenovo', 'mac']
>>> x =["lenovo","apple","mac","lenovo","boys","girls","23","Alex"]
>>> x.reverse()#翻转
>>> x
['Alex', '23', 'girls', 'boys', 'lenovo', 'mac', 'apple', 'lenovo']

8. 获取下标

代码语言:javascript复制
>>> x =["lenovo","apple","mac","lenovo","boys","girls","23","Alex"]
>>> x.index("lenovo")#只返回第一个元素的下标0
>>>
 

0 人点赞