参考http://docs.python.org/2/tutorial/datastructures.html#SECTION007110000000000000000
>>>li = ['a', 'b', 'c']
>>>li.extend(['d', 'e', 'f'])
>>>li
['a','b', 'c', 'd', 'e', 'f']
>>>li[-1]
'f'
>>>li.append(['d', 'e', 'f'])
>>>li
['a','b', 'c', ['d', 'e', 'f']]
li.insert(i,x) 在标号为i的元素处添加list x
li.remove(x)删除list x从li
li.pop([i]): 如果i缺省则删除list最后一个元素,如果不赋值,则删除标号为i的元素,这里'[]'表明i的赋值是可以选择的,非必须赋值变量
li.count(x):计算x出现的次数
li.sort():为li中所有元素排序
li.reverse():将li中所有元素反序
>>>a=[66.25,333,333,1,1234.5]
>>>printa.count(333),a.count(66.25),a.count('x')
2 1 0
>>>a.insert(2,-1)
>>>a.append(333)
>>>a[66.25, 333, -1, 333, 1, 1234.5, 333]
>>>a.index(333)
1
>>>a.remove(333)
>>>a[66.25, -1, 333, 1, 1234.5, 333]
>>>a.reverse()
>>>a
[333, 1234.5, 1, 333, -1, 66.25]
>>>a.sort()
>>>a
[-1, 1, 66.25, 333, 333, 1234.5]
list用成栈----先进后出
li.append
li.pop
list用成队列 要用collections.deque---先进先出
>>>fromcollectionsimportdeque
>>>queue=deque(["Eric","John","Michael"])
>>>queue.append("Terry")# Terry arrives
>>>queue.append("Graham")# Graham arrives
>>>queue.popleft()# The first to arrive now leaves'Eric'
>>>queue.popleft()# The second to arrive now leaves'John'
>>>queue# Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
当使用list时,有最重要的三个函数:filter(), map() 以及 reduce()
filter(function,sequence)
e.g.
>>>deff(x):returnx%2!=0andx%3!=0
...
>>>filter(f,range(2,25))
[5, 7, 11, 13, 17, 19, 23]
filter函数适用于逻辑函数,返回的是在range范围内,即2-24(包含)中使得f函数为真的值
map(function,sequence)
e.g.
>>>defcube(x):returnx*x*x
...
>>>map(cube,range(1,11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
map函数适用于对list整个处理,如果输入参数是两个变量的话,可以用map(cube,range1,range2)
reduce(function,sequence)
e.g.
>>>defadd(x,y):returnx+y
...
>>>reduce(add,range(1,11))
55
reduce函数返回的是一个值,通过函数add调用sequence的前两个值,计算得到的结果作为输入,再继续调用下一个值,适用于求累加或者累积
链表推导
e.g.1 >>>squares=[x**2forxinrange(10)]
e.g.2 >>>[(x,y)forxin[1,2,3]foryin[3,1,4]ifx!=y]
e.g.3 >>>vec=[[1,2,3],[4,5,6],[7,8,9]]
>>>[numforeleminvecfornuminelem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
e.g.4>>>matrix=[
...[1,2,3,4],
...[5,6,7,8],
...[9,10,11,12],
...]
>>>[[row[i]forrowinmatrix]foriinrange(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
与
>>>zip(*matrix)
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
等同
转载本文请联系原作者获取授权,同时请注明本文来自于博科学网博客。
链接地址:http://blog.sciencenet.cn/blog-571755-706769.html
上一篇:python中dictionary的用法小结
下一篇:python中tuple的用法