Lists are ordered collections
index从0开始
-1表示最后一个元素,-2表示倒数第二个,以此类推
bicycles = ['trek', 'cannondale', 'redline', 'specialized']message = f"My first bicycle was a {bicycles[0].title()}."print(message)
Changing, Adding, and Removing Elements
motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)# 修改motorcycles[0] = 'ducati'print(motorcycles)# 加到末尾motorcycles.append('ducati')print(motorcycles)# 插入motorcycles.insert(2, 'hhhh')print(motorcycles)# 从指定index移除del motorcycles[2]print(motorcycles)# 从末尾移除,并得到移除的值popped_motorcycle = motorcycles.pop()print(motorcycles)print(popped_motorcycle)# 从指定位置poppopped_motorcycle = motorcycles.pop(1)print(motorcycles)print(popped_motorcycle)# 删除指定值,remove只会删除第一个搜索到的值motorcycles = ['honda', 'yamaha', 'suzuki','honda']motorcycles.remove('honda')print(motorcycles)
Organizing a list
# sort按字母排序,改变自身cars = ['bmw', 'audi', 'toyota', 'subaru']cars.sort()print(cars)cars = ['bmw', 'audi', 'toyota', 'subaru']cars.sort(reverse=True)print(cars)# sorted不改变自身cars = ['bmw', 'audi', 'toyota', 'subaru']print(sorted(cars))print(sorted(cars, reverse=True))print(cars)# 反转cars.reverse()print(cars)# lengthprint(len(cars))
不允许的操作
python不允许给现有索引以外的范围赋值,而JS可以
cars = ['suzuki', 'BYD']cars[100] = 'qin' # Error list assignment index out of range
