在python中,列表,字典,有序字典的删除操作有些凌乱,所以决定记录下,以便以后用乱了。

列表:

列表删除有三种方式:

l.pop()

l.remove()

del l[3:8]

已下面的code为例,见注释:

l=['a','b','c','d','e','f','g','h','i','j','k',]
l.pop()  #pop()不带参数,因为列表是有序的,删除列表中最后一个元素
print(l)  
l.pop(3)  #pop()入带参数,参数为列表中的索引号,删除指定索引号的元素
print(l)
l.remove('c')  #remove(),删除列表中的对应元素,必须带参数,参数为列表中的元素
print(l)
del l[5]  #del 后面参数为list[index],索引也可为切片形式
print(l)
del l[1:3]
print(l)
del l  #如果直接del本身,删除被定义的变量
print(l) out:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Traceback (most recent call last):
File "/Users/shane/Desktop/中融腾更新文件/day3/test.py", line 55, in <module>
['a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j']
['a', 'b', 'e', 'f', 'g', 'h', 'i', 'j']
['a', 'b', 'e', 'f', 'g', 'i', 'j']
['a', 'f', 'g', 'i', 'j']
print(l)
NameError: name 'l' is not defined
[Finished in 0.1s with exit code 1]

字典:

字典中的删除也有三个,pop(),popitem(),del

还是以例子说明吧:

d={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,}
print(d)
d.pop('d')  #删除指定key以及key对应的value,因为列表是无序的,所有必须有参数,参数为列表中的指定key
print(d)
d.popitem()  #随机删除列表中的一条数据,括号中无参数
print(d)
del d['c']  #删除指定key,与pop相同,不同的是pop是圆括号,del是中括号,另外del可直接删除变量
print(d)

结果:

{'b': 2, 'j': 10, 'i': 9, 'f': 6, 'c': 3, 'e': 5, 'g': 7, 'd': 4, 'a': 1, 'h': 8}
{'b': 2, 'j': 10, 'i': 9, 'f': 6, 'c': 3, 'e': 5, 'g': 7, 'a': 1, 'h': 8}
{'j': 10, 'i': 9, 'f': 6, 'c': 3, 'e': 5, 'g': 7, 'a': 1, 'h': 8}
{'j': 10, 'i': 9, 'f': 6, 'e': 5, 'g': 7, 'a': 1, 'h': 8}
[Finished in 0.1s]

有序字典:

OrderedDict 有序字典,是字典的扩展,继承了字典的大部分功能。还是例子说明吧:

import collections
od=collections.OrderedDict()
od['xx']=23
od['ee']=21
od['ff']=33
od['aa']=11
od['bb']=22
print(od)
od.pop('xx')  #删除指定key,必须有参数,参数是key
print(od)
od.popitem()  #因为有序字典是有序列的,所以popitem()删除字典的最后一条数据
print(od)
del od['ee']  #同pop(),del 可删除变量
print(od) OUT:
OrderedDict([('xx', 23), ('ee', 21), ('ff', 33), ('aa', 11), ('bb', 22)])
OrderedDict([('ee', 21), ('ff', 33), ('aa', 11), ('bb', 22)])
OrderedDict([('ee', 21), ('ff', 33), ('aa', 11)])
OrderedDict([('ff', 33), ('aa', 11)])

做个总结图吧:

最新文章

  1. Firebug的下载安装
  2. redis初试牛刀
  3. 【风马一族_git_github】github项目建成网站
  4. RSA前台js加密,后台C#解密
  5. Jquery花园
  6. mysql 远程连接 2003 Can&#39;t connect to MySQL server (10060)
  7. js构造函数
  8. Android - Service启动机制
  9. BZOJ 1644: [Usaco2007 Oct]Obstacle Course 障碍训练课( BFS )
  10. atitit.提升稳定性---hibernate 添加重试retry 机制解决数据库连接关闭
  11. Linux安装Nginx以及简单理解
  12. 自定义SpringBoot启动banner
  13. 安装和使用git遇到的问题总结
  14. python selenium 爬取淘宝
  15. shell删除三天前或者三天内的文件
  16. winform使用相关
  17. Codeforces | CF1041F 【Ray in the tube】
  18. bootstrap之编译CSS和Javascript-0基础安装grunt教程
  19. 一些常见的第三方UI库
  20. hdu 3371 Connect the Cities(最小生成树)

热门文章

  1. k8s的监控
  2. Vue中在组件销毁时清除定时器(setInterval)
  3. 1127 模型层orm表操作
  4. webpack 配置react脚手架(六):api
  5. Airtest---UI自动化测试项目
  6. Mybatis接口中传递多个参数
  7. java类加载和对象初始化
  8. C++ 结构体指针的定义
  9. slax自启动程序
  10. Metaspace 之二--PermGen vs. Metaspace 运行时比较