在Python中按值切片浮点列表 [英] Slice List of floats by value in Python

查看:219
本文介绍了在Python中按值切片浮点列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个成千上万个浮点数的列表,希望能够按最小值和最大值进行切片.

I have a list of several thousand floats that I want to be able to slice by min and max values.

E.G.使用:

flist = [1.9842, 9.8713, 5.4325, 7.6855, 2.3493, 3.3333]

(我的实际列表是40万个浮点数,但以上是一个有效的示例)

(my actual list is 400,000 floats long, but the above is a working example)

我想要类似的东西

def listclamp(minn, maxn, nlist):

如此

print listclamp(3, 8, flist)

应该给我

[3.3333, 5.4325, 7.6855]

我还需要做10,000到30,000次,所以速度确实很重要.

I also need to do this 10,000 to 30,000 times, so speed does count.

(到目前为止,我没有尝试过的示例代码,因为这对我来说是新的python领域)

(I have no sample code for what I've tried so far, because this is new python territory for me)

推荐答案

这将返回您想要的排序列表:

This will return sorted list you want:

flist = [1.9842, 9.8713, 5.4325, 7.6855, 2.3493, 3.3333]

def listclamp(minn, maxn, nlist): 
    return sorted(filter(lambda x: xminn <= x <= maxn, nlist))

print listclamp(3, 8, flist) 

使用列表的更快方法理解力:

A faster approach, using list comprehensions:

def listclamp2(minn, maxn, nlist): 
    return sorted([x for x in flist if (minn <= and x<=maxn)])

print listclamp2(3, 8, flist)

请注意,根据您的数据,最好先过滤列表然后对其进行排序(就像我在上面的代码中所做的那样).

Note that depending on your data it may be better to filter the list first and then sort it (as I did in the code above).

有关性能的更多信息,请参见此链接.

For more information on performance, refer to this link.

这篇关于在Python中按值切片浮点列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆