Python中Array的常用操作(三)数组高级操作

1. 抽取数组中不重复的数据

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

>>> uniq = list(set(a))

[8, 2, 4, 6]

>>> uniq = sorted(set(a))

[2, 4, 6, 8]

>>> b={}

>>> for x in a:

… b[x]=1

>>> uniq = b.keys()

 

2. 去除在另一个数组中元素

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

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

 

>>> aonly = [x for x in a if x not in b]

 

>>> a_set = set(a)

>>> b_set = set(b)

>>> aonly = list(a_set - b_set)

3. 数组排序

>>> def comp(x,y):

… if x>y:

… return -1

… elif x==y:

… return 0

… else :

… return 1

>>> unsorted_list = [82, 67, 10, 46, 81, 40, 71, 88, 55]

>>> unsorted_list.sort(comp)

[88, 82, 81, 71, 67, 55, 46, 40, 10]

 

4. 两个数组交、并操作

 

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

[2, 4, 6, 8]

>>> b = [ x for x in range(3,7) ]

[3, 4, 5, 6]

>>> a_set = set(a)

>>> b_set = set(b)

# Union

>>> print list (a_set | b_set )

[2, 3, 4, 5, 6, 8]

#Intersection

>>> print list(a_set & b_set)

[4, 6]

#Difference

>>> print list(a_set ^ b_set)

[8, 2, 3, 5]

5. 数组函数map()、filter()、reduce()

a) map()

map(function,sequence)为每一个sequence的元素调用function(item) 并把返回值组成一个数组。

>>>

>>> def fun(x): return x*x

>>> print map(fun,range(0,5))

[0, 1, 4, 9, 16]

使用map(None,list1,list2)可以快速把两个数组变成元素对的一个数组

>>> print map(None,range(0,5),range(100,105))

[(0, 100), (1, 101), (2, 102), (3, 103), (4, 104)]

b) filter()

filter(function,sequence)返回一个序列,包含了所有调用function(item)后返回值为true的元素。

>>> unsorted_list = [82, 67, 10, 46, 81, 40, 71, 88, 55]

>>> def fun(x): return x%2==0

>>> print filter(fun,unsorted_list)

[88, 82, 46, 40, 10]

c) reduce()

reduce(function,sequence)返回一个单值,首先以数组的前两个元素调用函数function,在以返回值和第三个元素为参数调用,依次执行下去。

例如,以下程序计算1到10的整数的和

>>> def add(x,y): return x+y

>>> print reduce(add,range(0,11))

55

 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

多鱼的夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值