从列表中删除元素

内容纲要
  1. del 语句删除元素

    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)
    del motorcycles[1]
    print(motorcycles)
    ['honda', 'yamaha', 'suzuki']
    ['honda', 'suzuki']
  2. pop() 方法删除元素

    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)
    popped_motorcycle = motorcycles.pop()
    print(motorcycles)
    print(popped_motorcycle)
    ['honda', 'yamaha', 'suzuki']
    ['honda', 'yamaha']
    suzuki
  3. 弹出列表中任何位置处的元素

    motorcycles = ['honda', 'yamaha', 'suzuki']
    first_owned = motorcycles.pop(0)
    print(f"The last motorcycle I owned was a {first_owned.title()}.")
    The first motorcycle I owned was a Honda.

    区别:若从列表中删除一个元素,且不再以任何方式使用,可使用 del;若要在删除元素后还能继续使用,可使用 pop().

  4. 根据值删除元素

    motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
    print(motorcycles)
    motorcycles.remove('ducati')
    print(motorcycles)
    ['honda', 'yamaha', 'suzuki', 'ducati']
    ['honda', 'yamaha', 'suzuki']

    方法 remove() 只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来确保将每个值都删除。

留下评论

您的电子邮箱地址不会被公开。