python中操作list的方法

109 阅读1分钟
  1. append(x): 在列表的末尾添加一个元素 x
my_list = [1, 2, 3]
my_list.append(4)  # 结果:[1, 2, 3, 4]
  1. extend(iterable): 将可迭代对象 iterable 中的所有元素添加到列表末尾。
my_list = [1, 2, 3]
my_list.extend([4, 5])  # 结果:[1, 2, 3, 4, 5]
  1. insert(i, x): 在索引 i 的位置插入元素 x
my_list = [1, 3, 4]
my_list.insert(1, 2)  # 结果:[1, 2, 3, 4]
  1. remove(x): 移除列表中第一个出现的元素 x
my_list = [1, 2, 3, 2]
my_list.remove(2)  # 结果:[1, 3, 2]
  1. pop([i]): 移除并返回索引 i 处的元素,默认为最后一个元素。
my_list = [1, 2, 3]
popped_element = my_list.pop()  # popped_element: 3, my_list: [1, 2]
popped_element = my_list.pop(0)  # popped_element: 1, my_list: [2]
  1. clear(): 清空列表中的所有元素。
my_list = [1, 2, 3]
my_list.clear()  # 结果:[]
  1. index(x[, start[, end]]): 返回列表中第一个出现的元素 x 的索引,可以在指定范围内搜索。
my_list = [1, 2, 3, 2]
index = my_list.index(2)  # 结果:1
  1. count(x): 返回元素 x 在列表中出现的次数。
my_list = [1, 2, 3, 2]
count = my_list.count(2)  # 结果:2
  1. sort(key=None, reverse=False): 对列表进行排序,key 是排序关键字,reverse 表示是否逆序。
my_list = [3, 1, 2]
my_list.sort()  # 结果:[1, 2, 3]
my_list.sort(reverse=True)  # 结果:[3, 2, 1]
  1. reverse(): 反转列表中的元素顺序。
my_list = [1, 2, 3]
my_list.reverse()  # 结果:[3, 2, 1]
  1. copy(): 返回列表的浅拷贝。
my_list = [1, 2, 3]
new_list = my_list.copy()  # 结果:[1, 2, 3]