python关键字list_科学网—python中的list用法简单小结 - 于博的博文

参考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的用法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值