2022-12-23 00:44:40 +08:00
|
|
|
"""
|
2022-11-25 02:04:38 +08:00
|
|
|
File: list.py
|
|
|
|
Created Time: 2022-11-25
|
|
|
|
Author: Krahets (krahets@163.com)
|
2022-12-23 00:44:40 +08:00
|
|
|
"""
|
2022-11-25 02:04:38 +08:00
|
|
|
|
2023-04-09 05:30:02 +08:00
|
|
|
"""Driver Code"""
|
2022-11-25 03:59:38 +08:00
|
|
|
if __name__ == "__main__":
|
2023-04-09 05:05:35 +08:00
|
|
|
# 初始化列表
|
2023-10-09 18:20:42 +08:00
|
|
|
nums: list[int] = [1, 3, 2, 5, 4]
|
|
|
|
print("\n列表 nums =", nums)
|
2022-11-25 03:59:38 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 访问元素
|
2023-10-09 18:20:42 +08:00
|
|
|
x: int = nums[1]
|
|
|
|
print("\n访问索引 1 处的元素,得到 x =", x)
|
2022-11-25 03:59:38 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 更新元素
|
2023-10-09 18:20:42 +08:00
|
|
|
nums[1] = 0
|
|
|
|
print("\n将索引 1 处的元素更新为 0 ,得到 nums =", nums)
|
2022-11-25 03:59:38 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 清空列表
|
2023-10-09 18:20:42 +08:00
|
|
|
nums.clear()
|
|
|
|
print("\n清空列表后 nums =", nums)
|
2022-11-25 03:59:38 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 尾部添加元素
|
2023-10-09 18:20:42 +08:00
|
|
|
nums.append(1)
|
|
|
|
nums.append(3)
|
|
|
|
nums.append(2)
|
|
|
|
nums.append(5)
|
|
|
|
nums.append(4)
|
|
|
|
print("\n添加元素后 nums =", nums)
|
2022-11-25 03:59:38 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 中间插入元素
|
2023-10-09 18:20:42 +08:00
|
|
|
nums.insert(3, 6)
|
|
|
|
print("\n在索引 3 处插入数字 6 ,得到 nums =", nums)
|
2022-11-25 03:59:38 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 删除元素
|
2023-10-09 18:20:42 +08:00
|
|
|
nums.pop(3)
|
|
|
|
print("\n删除索引 3 处的元素,得到 nums =", nums)
|
|
|
|
|
|
|
|
# 遍历列表
|
|
|
|
tmp = []
|
|
|
|
for i in range(len(nums)):
|
|
|
|
tmp.append(nums[i])
|
|
|
|
print(f"\n通过索引遍历列表得到 tmp = {tmp}")
|
|
|
|
|
|
|
|
tmp.clear()
|
|
|
|
for num in nums:
|
|
|
|
tmp.append(num)
|
|
|
|
print(f"\n直接遍历列表元素得到 tmp = {tmp}")
|
2022-11-25 03:59:38 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 拼接两个列表
|
2023-10-09 18:20:42 +08:00
|
|
|
nums1 = [6, 8, 7, 10, 9]
|
|
|
|
nums += nums1
|
|
|
|
print("\n将列表 nums1 拼接到 nums 之后,得到 nums =", nums)
|
2022-11-25 03:59:38 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 排序列表
|
2023-10-09 18:20:42 +08:00
|
|
|
nums.sort()
|
|
|
|
print("\n排序列表后 nums =", nums)
|