0x2 Python学习之路之Python列表、元组操作

列表、元组操作


列表

定义列表:

names = ["China", "ShanDong", "LiaoCheng", "University"]

通过下标访问列表中的元素,下标从0开始计数

names = ["China", "ShanDong", "LiaoCheng", "University"]
print(names[0],names[2])#打印第一个names,打印下标为2的names

切片:取多个元素

names = ["China", "ShanDong", "LiaoCheng", "University"]
print(names[1:3])#切片
print(names[0:3])#切片
print(names[-1])
print(names[-2:0])#print(names[-2:])
print(names[0:3])#print(names[:3])

输出:
['ShanDong', 'LiaoCheng']
['China', 'ShanDong', 'LiaoCheng']
University
[]
['China', 'ShanDong', 'LiaoCheng']

追加:

names = ["China", "ShanDong", "LiaoCheng", "University"]
names.append("Dadaghe")#放到尾部
print(names)
#['China', 'ShanDong', 'LiaoCheng', 'University', 'Dadaghe']

插入:

names = ["China", "ShanDong", "LiaoCheng", "University"]
names.insert(1,"LiaoCheng")#插在下标1前面
names.insert(3,"ShanDong")#插在下标3前面
print(names)
#['China', 'LiaoCheng', 'ShanDong', 'ShanDong', 'LiaoCheng', 'University']

修改:

names = ["China", "ShanDong", "LiaoCheng", "University"]
names[2] = "QingHua"
print(names)
#['China', 'ShanDong', 'QingHua', 'University']

删除:

names = ["China", "ShanDong", "LiaoCheng", "University"]
#names.remove("LiaoCheng")
del names[3]
#names.pop(1) =del names[1]
print(names)
#['China', 'ShanDong', 'LiaoCheng']

获取下标:

names = ["China", "ShanDong", "LiaoCheng", "University"]
print(names.index("ShanDong"))#获取ShanDong下标
print(names[names.index("ShanDong")])#获取到ShanDong下标然后输入下标对应的names  其实这句话有点智障,哈哈
#1
#ShanDong

统计:

names = ["China", "ShanDong", "LiaoCheng", "University","ShanDong"]
print(names)
print(names.count("ShanDong"))
#['China', 'ShanDong', 'LiaoCheng', 'University', 'ShanDong']
#2

清空:

names = ["China", "ShanDong", "LiaoCheng", "University"]
names.clear()
print(names)

反转:

names = ["China", "ShanDong", "LiaoCheng", "University"]
names.reverse()
print(names)
#['University', 'LiaoCheng', 'ShanDong', 'China']

排序:

names = ["4China", "ShanDong", "#!LiaoCheng", "University"]
names.sort()
print(names)
#['#!LiaoCheng', '4China', 'ShanDong', 'University']按照ASCII码进行排序

扩展:

names = ["China", "ShanDong", "LiaoCheng", "University"]
names2 = [1,2,3,4]
names.extend(names2)
#del names2 //删除列表nemes2
print(names)
print(names2)
#['China', 'ShanDong', 'LiaoCheng', 'University', 1, 2, 3, 4]
#[1, 2, 3, 4]

元组

元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表

语法

names = ("China", "ShanDong", "LiaoCheng", "University")

它只有2个方法,一个是count,一个是index,完毕。

names = ("China", "ShanDong", "LiaoCheng", "University")
print(names.count("China"))
#1
#功能:获取元素在元组中的索引值,对于重复的元素,默认获取从左起第一个元素的索引值
names = ("China", "ShanDong", "LiaoCheng", "University","a","b")
T = names.index("a")
print(T)
#4

 

 

相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页