本文主要是介绍【重识python day4】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
列表得方法
list,列表类型,用于存储一些数据的容器(有序 & 可修改)、
tuple,元组类型,用于存储一些数据的容器(有序 & 不可修改)
不可变类型:字符串、布尔、整型(已最小,内部数据无法进行修改)
可变类型:列表(内部数据元素可以修改)
一、独有
1.1 、append() 追加,在原列表中尾部追加值
data_list = []v1 = input("请输入姓名")
data_list.append(v1)v2 = input("请输入姓名")
data_list.append(v2)print(data_list) # ["alex","eric"]
1.2 、extend() 批量追加,将一个列表中的元素逐一添加另外一个列表
tools = ["搬砖","菜刀","榔头"]
tools.extend( [11,22,33] ) # weapon中的值逐一追加到tools中
print(tools) # ["搬砖","菜刀","榔头",11,22,33]
1.3 、insert() 插入,在原列表的指定索引位置插入值
user_list = ["苍老师","有坂深雪","大桥未久"]
user_list.insert(0,"马蓉")
user_list.insert(2,"李小璐")
print(user_list)
['马蓉', '苍老师', '李小璐', '有坂深雪', '大桥未久']
1.4 、remove() 在原列表中根据值删除(从左到右找到第一个删除)【慎用,里面没有会报错】
user_list = ["王宝强","陈羽凡","Alex","贾乃亮","Alex"]
user_list.remove("Alex")
print(user_list)['王宝强', '陈羽凡', '贾乃亮', 'Alex']user_list = ["王宝强","陈羽凡","Alex","贾乃亮","Alex"]
if "Alex" in user_list:user_list.remove("Alex")
print(user_list)['王宝强', '陈羽凡', '贾乃亮', 'Alex']user_list = ["王宝强","陈羽凡","Alex","贾乃亮","Alex"]
while True:if "Alex" in user_list:user_list.remove("Alex")else:break
print(user_list)['王宝强', '陈羽凡', '贾乃亮']
1.5 、pop() 在原列表中根据索引踢出某个元素(根据索引位置删除)
user_list = ["王宝强","陈羽凡","Alex","贾乃亮","Alex"]# 0 1 2 3 4user_list.pop(1)
print(user_list) # ["王宝强","Alex","贾乃亮","Alex"]user_list.pop()
print(user_list) # ["王宝强","Alex","贾乃亮"]item = user_list.pop(1)
print(item) # "Alex"
print(user_list) # ["王宝强","贾乃亮"]
1.6 、clear() 清空原列表
user_list = ["王宝强","陈羽凡","Alex","贾乃亮","Alex"]
user_list.clear()
print(user_list) # []
1.7 、index() 根据值获取索引(从左到右找到第一个删除)【慎用,找不到报错】
user_list = ["王宝强","陈羽凡","Alex","贾乃亮","Alex"]
# 0 1 2 3 4
if "Alex" in user_list:index = user_list.index("Alex")print(index) # 2
else:print("不存在")
1.8 、sort() 列表元素排序
# 数字排序
num_list = [11, 22, 4, 5, 11, 99, 88]
print(num_list)
num_list.sort() # 让num_list从小到大排序
num_list.sort(reverse=True) # # 让num_list从大到小排序
print(num_list)# 字符串排序
user_list = ["王宝强", "Ab陈羽凡", "Alex", "贾乃亮", "贾乃", "1"]
# [29579, 23453, 24378]
# [65, 98, 38472, 32701, 20961]
# [65, 108, 101, 120]
# [49]
print(user_list)
"""
sort的排序原理[ "x x x" ," x x x x x " ]
"""
user_list.sort()
print(user_list) #['1', 'Ab陈羽凡', 'Alex', '王宝强', '贾乃', '贾乃亮']
注意:排序时内部元素无法进行比较时,程序会报错(尽量数据类型统一)
1.9 、reverse() 反转原列表
user_list = ["王宝强","陈羽凡","Alex","贾乃亮","Alex"]
user_list.reverse()print(user_list)
# ['Alex', '贾乃亮', 'Alex', '陈羽凡', '王宝强']
这篇关于【重识python day4】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!