python列表1_3

127 阅读1分钟

8、列表的删除

  • del 索引删除, 不指定索引 整个删除
list1 = ['a', 'b', 'c']
del list1[0]
# ['b', 'c']
print(list1)

# ===============

list1 = ['a', 'b', 'c']
del list1
# 报错 NameError: name 'list1' is not defined
print(list1)
  • remove 指定删除哪一个
list1 = ['a', 'b', 'c']
list1.remove('c')
# ['a', 'b']
print(list1)
  • pop 从列表里拿走一个值

不传递参数, 拿去最后一个, 有个索引参数可选, 写了这个参数, 就按索引值删除

list1 = ['a', 'b', 'c']
list1.pop()  # 没参数 拿走最后一个, 有一个可选参数是索引, 根据索引值拿去 相当于有list1.pop(-1)
# ['a', 'b']
print(list1)

# ==========================

list1 = ['a', 'b', 'c']
list1.pop(1)
# ['a', 'c']
print(list1)
  • 清空列表 clear
list1 = ['a', 'b', 'c']
list1.clear()
# []
print(list1)

9、列表的修改

根据索引值来修改

list1 = ['a', 'b', 'c']
list1[0] = 'A'
# ['A', 'b', 'c']
print(list1)

10、反序: 将列表顺序倒过来

reverse 方法

list1 = ['a', 'b', 'c']
list1.reverse()
# ['c', 'b', 'a']
print(list1)

11、排序:对数字

sort 方法

默认 升序或者 加参数reverse=False 也是升序, 加参数reverse=True 降序

list1 = [5, 9, 15]
list1.sort()
# [5, 9, 15]
print(list1)

#==================

list1 = [5, 9, 15]
list1.sort(reverse=True)
# [15, 9, 5]
print(list1)