Python 列表中常用的方法整理

以下是 Python 列表中常用的方法:

方法描述
list.append(x)把一个元素添加到列表的结尾,相当于 a[len(a):] = [x]
list.extend(L)通过添加指定列表的所有元素来扩充列表,相当于 a[len(a):] = L
list.insert(i, x)在指定位置插入一个元素。第一个参数是准备插入到其前面那个元素的索引,例如 a.insert(0, x) 会插入到整个列表之前,而 a.insert(len(a), x) 相当于 a.append(x)
list.remove(x)删除列表中值为 x 的第一个元素。如果没有这样的元素,就会返回一个错误
list.pop([i])从列表的指定位置移除元素,并将其返回。如果没有指定索引,那么 a.pop() 返回最后一个元素。元素随即从列表中被移除。注意,该方法中 i 两边的方括号表示这个参数是可选的,而不是要求输入一对方括号
list.clear()移除列表中的所有项,等于 del a[:]
list.index(x)返回列表中第一个值为 x 的元素的索引。如果没有匹配的元素就会返回一个错误
list.count(x)返回 x 在列表中出现的次数
list.sort()对列表中的元素进行排序
list.reverse()倒排列表中的元素
list.copy()返回列表的浅复制,等于 a[:]

示例代码:

定义如下一个列表:

list_ = [1, 3, 2, 4]
  • list.append(x)
list_.append(5)
print(list_)

# 运行结果:
[1, 3, 2, 4, 5]
  • list.extend(L)
list2 = [5, 6]
list_.extend(list2)
print(list_)

# 运行结果:
[1, 3, 2, 4, 5, 6]
  • list.insert(i, x)
list_.insert(0, 0)
print(list_)

# 运行结果:
[0, 1, 3, 2, 4]
  • list.remove(x)
list_.remove(2)
print(list_)

# 运行结果:
[1, 3, 4]
  • list.pop([i])
print(list_.pop(1))

# 运行结果:
3
[1, 2, 4]
print(list_.pop())

# 运行结果:
4
[1, 3, 2]
  • list.clear()
list_.clear()
print(list_)

# 运行结果:
[]
  • list.index(x)
print(list_.index(3))

# 运行结果:
1
  • list.count(x)
print(list_.count(3))

# 运行结果:
1
  • list.sort()
list_.sort()
print(list_)

# 运行结果:
[1, 2, 3, 4]
  • list.reverse()
list_.reverse()
print(list_)

# 运行结果:
[4, 2, 3, 1]
  • list.copy()
list2 = list_.copy()
print(list2)

# 运行结果:
[1, 3, 2, 4]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值