python取一个范围内的所有数字_在一个范围内查找数字对分python

我会用numpy来做这个,特别是如果列表那么长的话。例如:In [101]: list = np.array([4,2,1,7,9,4,3,6,8,97,7,65,3,2,2,78,23,1,3,4,5,67,8,100])

In [102]: list

Out[102]:

array([ 4, 2, 1, 7, 9, 4, 3, 6, 8, 97, 7, 65, 3,

2, 2, 78, 23, 1, 3, 4, 5, 67, 8, 100])

In [103]: good = np.where((list > 4) & (list < 20))

In [104]: list[good]

Out[104]: array([7, 9, 6, 8, 7, 5, 8])

# %timeit says that numpy is MUCH faster than any list comprehension:

# create an array 10**6 random ints b/w 0 and 100

In [129]: arr = np.random.randint(0,100,1000000)

In [130]: interval = xrange(4,21)

In [126]: %timeit r = [x for x in arr if x in interval]

1 loops, best of 3: 14.2 s per loop

In [136]: %timeit good = np.where((list > 4) & (list < 20)) ; new_list = list[good]

100 loops, best of 3: 10.8 ms per loop

In [134]: %timeit r = [x for x in arr if 4 < x < 20]

1 loops, best of 3: 2.22 s per loop

In [142]: %timeit filtered = [i for i in ifilter(lambda x: 4 < x < 20, arr)]

1 loops, best of 3: 2.56 s per loop

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值