在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)])
做个总结图吧: