Monday, 14 January 2008

Python中Array的常用操作数组基本操作

1. 定义数组

>>> seq = [ “a” , “b” , 1 ]

[ “a” , “b” , 1 ]

2. 创建数组

>>> a = “what are you doing?”.split()

[’what’, ‘are’, ‘you’, ‘doing?’]

>>> a = [ x*2 for x in range(1,5) ]

[2, 4, 6, 8]

b = [ x for x in a if x >3 ]

[ 4, 6, 8]

-----------------------------------------------------------

1. 数组操作

x代表数组中的元素,i代表位置

a) append(x) 把元素x添加到数组的尾部

b) insert(i,x) 把元素x 插入到位置i

c) remove(x) 删除第一个元素x

d) pop(i) 删除第i个元素,并返回这个元素。若调用pop()则删除最后一个元素

e) index(x) 返回数组中第一个值为x的位置。如果没有匹配的元素会抛出一个错误

f) count(x) 返回x在数组中出现的次数

g) sort() 对数组中的元素进行排序

h) reverse() 对数组中的元素用倒序排序

>>> a = [ x*2 for x in range(1,5) ]

[2, 4, 6, 8]

>>> del a[0]

[4, 6, 8]

>>> a = [ 1 , 2 ] + a

[1, 2, 4, 6, 8]

>>> a += [None]*2

[1, 2, 4, 6, 8, None, None]

>>> a.remove(1)

[2, 4, 6, 8, None, None]

>>> a.pop()

[2, 4, 6, 8, None,]

>>> a.append(100)

[2, 4, 6, 8, None, 100]

>>> a.insert(0,8)

[8, 2, 4, 6, 8, None, 100]

>>> a.count(8)

2

>>> a.index(2)

1

2. 遍历数组

>>> a = [ x*2 for x in range(1,5) ]

[2, 4, 6, 8]

>>> for x in a:

… print x

>>> for i, x in enumerate(a):

… print x

>>> b = [ x+100 for x in a]

>>> for i,j in zip(a,b):

… print i,j

No comments:

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter