python的列表及元组
一.python列表
1.列表的介绍
列表就像是一个容器,存储想要存储的数据,使用[]存储,使用,分隔每个值。
2.列表格式
列表的格式:变量A的类型为列表
列表 变量=[]
namesList = [‘xiaoWang’,‘xiaoZhang’,‘xiaoHua’]
比C语言,java等数组强大的地方在于列表中的元素可以是不同类型的
testList = [1, ‘a’]
3.列表的打印
myTestList = [“张三”, 456, “哈哈”, “朕没疯”]
print(myTestList[0])
print(myTestList[1])
print(myTestList[2])
print(myTestList[3])
4.for循环打印列表中的内容
// for循环打印列表中的内容
myTestListlength = len(myTestList)
myTestList = ["张三", 456, "哈哈", "朕没疯"]
5.while循环打印列表中的内容
// while循环打印列表中的内容
myTestListlength = len(myTestList)
i = 0
while i < myTestListlength:
print(myTestList[i])
i += 1
二.python列表的操作
介绍:
列表中存放的数据是可以进行修改的,比如"增"、“删”、“改”、“查”
1.列表的添加(append, extend, insert)
(1)、append可以向列表尾部添加元素。
// append案例:
myTestList = ["张三", 456, "哈哈", "朕没疯"]
myTestList.append("哈啊哈哈哈哈")
for i in myTestList:
print(i)
(2)、extend 通过extend可以将另一个集合中的元素逐一添加到列表中
// extend案例:
a = [1, 2, 3]
b = [9, 7, 8]
a.extend(b)
print(a)
extend和append的区别:
(3)、insert(index, object) 在指定位置index前插入元素object
// insert案例:
a = [1, 2, 3]
a.insert(1,555)
print(a)
2.列表的修改
修改元素的时候,要通过下标来确定要修改的是哪个元素,然后才能进行修改
// 列表修改案例:
myTestList = ["张三", 456, "哈哈", "朕没疯"]
myTestList[2]="我喜欢她啊"
for i in myTestList:
print(i)
3.列表的查找(in, not in, index, count)
所谓的查找,就是看看指定的元素是否存在
in, not in
python中查找的常用方法为:
in(存在),如果存在那么结果为true,否则为false
not in(不存在),如果不存在那么结果为true,否则false
(1)、in(存在),如果存在那么结果为true,否则为false
// in案例:
myTestList = ["张三", 456, "哈哈", "朕没疯"]
findname="哈哈"
if findname in myTestList:
print("有%s"%findname)
else:
print("没有这个玩意")
not in 与in是相反的 就不演示了
(2)、index(查询索引)和(查询个数)与字符串中的用法一致
// count案例:查询a的个数
myList = ["a", "c", 'b', 'a', 'q']
ll = myList.count("a")
print(ll)
下图展示有两个a
// index(索引)案例:查询a的索引
myList = ["a", "c", 'b', 'a', 'q']
lli = myList.index("a")
print(ll)
会查询第一个a的索引,索引为0
4.列表的删除(del, pop, remove)
列表元素的常用删除方法有:
del:根据下标进行删除
pop:删除最后一个元素
remove:根据元素的值进行删除
(1)、del 根据下标进行删除
// 案例:del 根据下标进行删除
myTestList = ["张三", 456, "哈哈", "朕没疯"]
del myTestList[1]
for i in myTestList:
print(i)
(2)、pop:删除最后一个元素
// 案例:pop 删除最后一个元素
myTestList = ["张三", 456, "哈哈", "朕没疯"]
myTestList.pop()
for i in myTestList:
print(i)
(3)、remove:根据元素的值进行删除
// 案例:remove 根据元素的值进行删除
myTestList = ["张三", 456, "哈哈", "朕没疯"]
myTestList.remove("张三")
for i in myTestList:
print(i)
5.列表的排序(sort, reverse)
sort方法是将list按特定顺序重新排列,默认为由小到大,参数reverse=True可改为倒序,由大到小。
reverse方法是将list逆置。
(1)、sort排序
// sort排序案例:
a = [5, 7, 1, 2, 3, 9, 6]
a.sort()
print(a)
(2)、reverse反转
// sort排序案例:
a = [5, 7, 1, 2, 3, 9, 6]
a.reverse()
print(a)
6.列表的嵌套
一个列表中的元素又是一个列表,那么这就是列表的嵌套
示例:
schoolNames = [[‘北京大学’, ‘清华大学’],
[‘南开大学’, ‘天津大学’, ‘天津师范大学’],
[‘浙江大学’], [‘河北大学’, ‘河北科技大学’]]
练习:
// 取出河北科技大学
print(schoolNames[3][1])
// 删除 河北大学
schoolNames[3].pop()
print(schoolNames)
// 插入 河北农业大学
schoolNames[3].insert(2, "河北农业大学")
print(schoolNames)
三.元组
1.元组的介绍
Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。
元组无法进行增删改。但可以拼接。
// 元组的打印
aTuple = (1, 9, 7, 5, 6, 2,)
for i in aTuple:
print(i)
2.列表转元组
// 列表转元组案例
lists = [1, 2, 3, 4, 5]
a = tuple(lists)
print(a)
( ̄▽ ̄)~*------ ٩(๑❛ᴗ❛๑)۶谢谢阅读!!!!!!!!!!!!!