标签:删除指定元素 blog 删除元素 figure log 数据类型 元素 一个 col
python中内置了一种数据类型,列表。
list list是一种内置的有序的集合。可以随时实现list中的数据的添删改除。
list用 [] 来表示。
1 >>> figure = [‘1‘,‘2‘,‘3‘] 2 >>> print(figure) 3 [‘1‘, ‘2‘, ‘3‘]
上图中的figure就是一个list。
用 len() 函数可以查询输出该list中的元素个数。
1 >>> len(figure) 2 3
len()-1可以查询到该list中的最后一个元素的位置。
>>> a = [‘a‘,‘b‘,‘c‘,‘d‘] >>> len(a)-1 3 >>> len(a)-2 2
可以用 索引 来具体查询到某个元素。索引从 0 开始。
>>> figure[0] ‘1‘ >>> figure[1] ‘2‘ >>> figure[2] ‘3‘ >>> figure[3] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
如果元素索引超出了所查元素的范围时会报错。
也可以倒着来查询,最后一个是 -1 ,以此类推,倒数第二个是 -2 等。
>>> figure[-1] ‘3‘ >>> figure[-2] ‘2‘ >>> figure[-3] ‘1‘ >>> figure[-4] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
list是可变的有序列表,所以可以实现在list末尾追加元素。 .append 方法。
>>> figure.append(‘4‘) >>> figure [‘1‘, ‘2‘, ‘3‘, ‘4‘]
也可以用函数实现在指定位置添加元素。 .insert 方法。
>>> figure.insert(0,‘0‘) >>> figure [‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘]
也可以实现list的删除元素。
>>> figure.pop() ‘4‘ >>> figure [‘0‘, ‘1‘, ‘2‘, ‘3‘]
当 () 里无指定则默认删除最后一位元素。
>>> figure.pop() ‘4‘ >>> figure [‘0‘, ‘1‘, ‘2‘, ‘3‘]
当 pop() 指定元素的位置时则删除指定元素
>>> figure.pop(0) ‘0‘ >>> figure [‘1‘, ‘2‘, ‘3‘]
也可以直接给指定位置的元素重新赋值。
>>> figure[0] = ‘2‘ >>> figure [‘2‘, ‘2‘, ‘3‘]
list里可以同时放入不同类型的元素。
>>> L = [‘A‘,123,True] >>> L [‘A‘, 123, True]
list也可以相互嵌套。
>>> s = [‘a‘,‘b‘,‘c‘,[‘1‘,‘2‘,‘3‘],‘d‘] >>> s [‘a‘, ‘b‘, ‘c‘, [‘1‘, ‘2‘, ‘3‘], ‘d‘] >>> len(s) 5 >>> len(s)-1 4 >>> s[-1] ‘d‘ >>> s[-2] [‘1‘, ‘2‘, ‘3‘]
>>> r = [True] >>> r [True] >>> s.insert(3,r) >>> s [‘a‘, ‘b‘, ‘c‘, [True], [‘1‘, ‘2‘, ‘3‘], ‘d‘]
这种两个list嵌套的称为 二维数组 ,定位二维需要 [][] 定位,像纵横坐标一样,三维则需要 [][][] ,以此类推。
>>> s [‘a‘, ‘b‘, ‘c‘, [True], [‘1‘, ‘2‘, ‘3‘], ‘d‘] >>> print(s[4][0]) 1
如果建立一个空的list也是可行的。
>>> a = [] >>> a [] >>> len(a) 0
标签:删除指定元素 blog 删除元素 figure log 数据类型 元素 一个 col
原文地址:http://www.cnblogs.com/dymlnet/p/7789133.html