列表
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
#Accessing Elements in a List
print(bicycles[0])#第一个元素
print(bicycles[0].title())
#Accessing the Last Element in a List
print(bicycles[-1])#最后一个元素
#Using Individual Values from a List
message1 = "My first bicycle was a " + bicycles[0].title() + "."
print(message1)
message2 = f"My first bicycle was a {bicycles[0].title()}."
print(message2)
修改
#Changing, Adding, and Removing Elements
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles) #Change an Element修改元素
motorcycles[0] = 'ducati'
print(motorcycles)
添加
mototcycles = ["honda", "yamaha", "suzuki"]
print(mototcycles)
mototcycles.append("ducati")#附加
print(mototcycles)
moto = []
moto.append("ducati")
print(moto)
插入
mototcycles = ["honda", "yamaha", "suzuki"]
print(mototcycles)
mototcycles.insert(0, "ducati")#既有的每个元素右移
print(mototcycles)
删除
mototcycles = ["honda", "yamaha", "suzuki"]
print(mototcycles)
del mototcycles[0]#del语句删除列表中的元素
print(mototcycles)
print(mototcycles.pop(1))#pop()方法删除列表中的元素,并返回该元素的值
#在三体人消失的地方显示爆炸效果
#用此方法,moto被不停重新赋值,列表不断变短
#不用pop,用popped_moto重新赋值也可
print(mototcycles.pop())
gel = "was, is, are, am"
#这里用pop()会怎么样
CodeGeeX
在Python中,pop()
方法通常用于列表。它用于移除列表中的一个元素(默认为最后一个元素),并返回该元素的值。由于 gel
是一个字符串,而不是列表,所以直接在这个字符串上使用 pop()
方法会导致 AttributeError
。如果您想要从字符串中移除某些字符或子字符串,您需要使用字符串的其他方法,如 replace()
或切片操作。*被pop的还能继续用,del不能
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
#print(motorcycles.remove('honda'))# remove()方法删除列表中的元素,但不会返回任何值None
motorcycles.remove('honda')#remove不知道位置,只知道要删除的元素
print(motorcycles)
too_expensive = 'honda'
print(f"\nA {too_expensive.title()} is too expensive for me.")
组织排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()#永久性排序,字母顺序
#print(cars.sort())#没有返回值,输出none
print(cars)
cars.sort(reverse=True)#倒序
print(cars)
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars, reverse=True)) # 临时排序 sorted() does not change the original list
print("Here is the original list again:")
print(cars)
cars.reverse() # 倒叙,永久排序
print(cars)
length = len(cars)# 获取列表长度
print(length)
索引错误解决:打印列表长度