#####################列表基础#############################
# 3 列表是什么
club = ["hotspurs","livepool","manchester city","Chelsea","arsenal","..."]
print(club)
# 访问列表元素
print(club[2])
print(club[2].title())
## 使用列表中的元素
massage = "我最喜欢的足球队是---"+club[4].title()+"."
print(massage)
## 修改列表中的元素
club[len(club)-1] = "manchester united"
print(club)
## 在列表尾部追加元素
club.append("Leicester City")
print(club)
## 在列表插入元素
club.insert(0,"Southampton")
print(club)
## 注意虽然此时列表没有索引9,但是python并不会报错,而是插入到最后
club.insert(9,"Wolverhampton")
print(club)
## 从列表中删除元素 方法1:使用del语句
print("删除第一个之前:",club)
del club[0]
print("删除第一个之后:",club)
## 从列表中删除元素 方法2:使用pop()方法
club_pop = club.pop()
print(club_pop)
print(club)
## 从列表中删除元素 方法3:弹出任意位置的元素使用pop(index)方法
club_pop1 = club.pop(2)
print(club_pop1)
print(club)
## 从列表中删除元素 方法4:根据值删除
club.remove("arsenal")
print(club)
##########################组织列表#####################################
## 方法sort对列表永久排序
cars = ['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
cars.sort(reverse=True)
print(cars)
## 方法sorted对列表临时排序
cars = ['bmw','audi','toyota','subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
## 方法reverse()对列表倒置(永久性)
print(cars)
cars.reverse()
print(cars)
## 方法lene()对列表求长度
print(len(cars))
【python基础】初识列表
最新推荐文章于 2023-05-17 15:07:35 发布