假期第(9)天
列表元素访问
l 用下标直接访问列表元素,若下标不存在则抛出异常
>>> aList[3] = 5.5
>>> aList
[3, 4, 5, 5.5, 7, 9, 11, 13, 15, 17]
>>> aList[15]
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
aList[15]
IndexError: list index out of range
l 列表对象的index()方法获取指定元素首次出现的下标,
若列表对象中不存在指定元素则抛出异常。
>>> aList.index(7)
4
>>> aList.index(100)
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
aList.index(100)
V
al
ue
Er
ror
: 100 is not in list
列表与列
表
推
导
式2
3
23
列表元素的计数
l 列表对象的count()方法统计指定元素在列表对象中出
现的次数。
>>> aList
[3, 4, 5, 5.5, 7, 9, 11, 13, 15, 17]
>>> aList.count(7)
1
>>> aList.count(0)
0
>>> aList.count(8)
0
列表与列表推导式2
4
2
4
成员资格判断
l in关键字来判断一个值是否存在于列表中,返回值为
"True"或"False"
>>> bList = [[1], [2], [3]]
>>> 3 in bList
False
>>> 3 not in bList
True
>>> [3] in bList
True
>>> aList = [3, 5, 7, 9, 11]
>>> bList = ['a', 'b', 'c', 'd']
>>> (3, 'a') in zip(aList, bList)
True
>>> for a, b in zip(aList, bList):
print(a, b)
列表与列表推导式2
5
25
列表排序-1
l 列表对象的sort()方法进行原地排序,支持多种不同
的排序方法。
>>> aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
>>> import random
>>> random.shuffle(aList)
>>> aList
[3, 4, 15, 11, 9, 17, 13, 6, 7, 5]
>>> aList.sort() #默认是升序排序
>>> aList.sort(reverse = True) #降序排序
>>> aList
[17, 15, 13, 11, 9, 7, 6, 5, 4, 3]
>>> aList.sort(key = lambda x:len(str(x)))#按转换成字符串的长度
排序
>>> aList
[9, 7, 6, 5, 4, 3, 17, 15, 13, 11]
列表与列表推导式2
6
2
6
列表排序-2
l 使用内置函数sorted()对列表进行排序并返回新列表
>>> aList
[9, 7, 6, 5, 4, 3, 17, 15, 13, 11]
>>> sorted(aList) #升序排序
[3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
>>> sorted(aList,reverse = True) #降序排序
[17, 15, 13, 11, 9, 7, 6, 5, 4, 3]
l 列表对象的reverse()方法将元素原地逆序
>>> aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
>>> aList.reverse()
>>> aList
[17, 15, 13, 11, 9, 7, 6, 5, 4, 3]
列表与列表推导式2
7
27
列表排序-3
l 使用内置函数reversed()对列表元素进行逆序排列并
返回迭代对象
>>> aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
>>> newList = reversed(aList) #返回reversed对象
>>> list(newList)
#把reversed对象转换成列表
[17, 15, 13, 11, 9, 7, 6, 5, 4, 3]
>>> for i in newList:
print(i, end=' ')
#由于迭代对象惰性计算,没有输出内容
>>> newList = reversed(aList) #重建reversed对象
>>> for i in newList:
print(i, end=' ')
17 15 13 11 9 7 6 5 4 3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App