列表练习
name = ["Jane","Max","Mack"]
print(name[0],name[1],name[2])
print(name[0] + ". Nice to meet you !")
追加元素
names = []
names.append("May")
names.append("Tony")
print(names)
插入元素,需要指定新元素的索引和值
names = ["Jane","Max","Mack"]
names.insert(1,"Tom")
print(names)
删除(del语句)
names = ["Jane","Max","Mack"]
del names[2]
print (names)
删除(pop()方法,弹出末尾元素)
names = ["Jane","Max","Mack"]
names.append("Tony")
print(names)
popped_name = names.pop()
print(names)
print(popped_name)
删除(pop(i),弹出列表中指定位置的元素)
names_new = ["Jane","Max","Mack"]
second_people = names_new.pop(1)
print("Second people is " + second_people)
删除(remove方法,根据值删除元素)
names_new = ["Jane","Max","Mack"]
names_new.remove("Jane")
print(names_new)
永久排序(sort()方法)
cars = ["bwm","audi","toyota"]
#字母正序
cars.sort()
print(cars)
#字母倒序
cars.sort(reverse=True)
print(cars)
临时排序(sorted()函数)
cars = ["bwm","audi","toyota"]
print(sorted(cars))
print(sorted(cars,reverse=True))
print(cars)
倒着打印列表
cars = ["bwm","audi","toyota"]
cars.reverse()
print(cars)
获取列表长度
cars = ["bwm","audi","toyota"]
print(len(cars))
使用for循环获取列表中所有元素
cars = ["bwm","audi","toyota"]
for car in cars:
print(car)
创建列表
#创建数字列表
numbers = list(range(1,6))
print(numbers)
even_numbers = list(range(2,11,2))
print(even_numbers)
#创建列表,包含前十个整数的平方
squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)
利用切片复制列表
list1 = ["a","b","c","d"]
list2 = list1[:]
list1.append("e")
list2.append("f")
print(list1,list2)
print("The firt three items in the list are: " )
for item in list1[-2:]:
print(item)
本文详细介绍Python列表的基本操作,包括元素的增删改查、排序、反转及长度获取等,通过实例展示列表的灵活运用,适合初学者快速掌握列表操作技巧。
—— 列表&spm=1001.2101.3001.5002&articleId=108438401&d=1&t=3&u=a6996fe42ba4419f98f0cdfb0b7a65e1)
535

被折叠的 条评论
为什么被折叠?



