索引 -1 返回列表最后一个元素,-2 返回倒数第二个列表元素,依次类推。

在列表中添加元素

在末尾添加元素 - append

  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. motorcycles.append('ducati')
  3. print(motorcycles) # ['honda', 'yamaha', 'suzuki', 'ducati']

在列表中插入元素 - insert

  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. motorcycles.insert(0, 'ducati')
  3. print(motorcycles) # ['ducati', 'honda', 'yamaha', 'suzuki']

从列表中删除元素

根据索引删除元素

del

使用 del 可删除列表中具体索引位置的元素。

  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. del motorcycles[0]
  3. print(motorcycles) # ['yamaha', 'suzuki']

pop

pop() 弹出列表中最后一个元素并返回该元素。可以通过传入索引,弹出索引位置处的元素。

  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. last_owned = motorcycles.pop()
  3. print(motorcycles) # ['honda', 'yamaha']
  4. print(last_owned) # suzuki
  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. first_owned = motorcycles.pop(0)
  3. print(motorcycles) # ['yamaha', 'suzuki']
  4. print(first_owned) # honda

根据值删除元素

remove

remove() 删除列表中第一个指定的值。

  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. motorcycles.remove('honda')
  3. print(motorcycles) # ['yamaha', 'suzuki']
  1. motorcycles = ['honda', 'yamaha', 'suzuki', 'honda']
  2. motorcycles.remove('honda')
  3. # 只删除了第一个
  4. print(motorcycles) # ['yamaha', 'suzuki', 'honda']

组织列表

使用 sort() 对列表永久排序

  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. motorcycles.sort()
  3. print(motorcycles) # ['honda', 'suzuki', 'yamaha']

传入 reverse=True 可以倒序排列

  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. motorcycles.sort(reverse = True)
  3. print(motorcycles) # ['yamaha', 'suzuki', 'honda']

使用 sorted() 对列表临时排序

  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. print(sorted(motorcycles)) # ['honda', 'suzuki', 'yamaha']
  3. print(motorcycles) # ['honda', 'yamaha', 'suzuki']

可以传入 reverse=True 作为 sorted() 第二个参数对列表进行临时倒序排序

  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. print(sorted(motorcycles, reverse = True)) # ['yamaha', 'suzuki', 'honda']
  3. print(motorcycles) # ['honda', 'yamaha', 'suzuki']

使用 reverse() 倒着打印列表

  1. motorcycles = ['bmw', 'audi', 'toyota', 'subaru']
  2. motorcycles.reverse()
  3. print(motorcycles) # ['subaru', 'toyota', 'audi', 'bmw']

使用 len() 确定列表长度

  1. motorcycles = ['bmw', 'audi', 'toyota', 'subaru']
  2. print(len(motorcycles)) # 4