Py学习  »  Python

在Python中,确定大于阈值的列表项的最有效方法是什么?

Hossein Rahimi • 4 年前 • 575 次点击  

基本上,我想知道什么是 最有效的方法 查找值大于,例如n的python列表元素。

我相信,最简单但效率不高的方法如下:

for i in range(len(theList)):
    if theList[i] > n:
        subList.append(theList[i])

而且,我们有单行线 for 如下所示:

(subList for subList in theList if sublist > n)

(如果上述语法有任何错误,请纠正我)

最后,我们可以使用 filter() 功能,这是不愉快的使用,至少对我来说。

以上方法都是我所知道的。如果你知道更好的方法,请告诉我。否则,请从效率和 运行时间 .

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38235
 
575 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Ijaz Ahmad Khan
Reply   •   1 楼
Ijaz Ahmad Khan    5 年前

列表理解版本:

sublist = [ i for i in the_list if i > n ]

生成器表达式:(如果列表太大)

sublist = ( i for i in the_list if i > n )
jojo
Reply   •   2 楼
jojo    5 年前

没有 总是对的 回答这个问题,有一些关于处理列表时不同方法的速度的帖子,请参见例如。 here , here here .

最快的方法是什么?可能很大程度上取决于你的清单。 也就是说,让我们看看建议的方法有多快。

对于这样的简单比较,您可以使用 timeit :

1。案例:for循环

for_case = """newList=[]
for x in theList:
    if x > n:
            newList.append(x)"""

2。案例:列表理解

list_comp = '[x for x in theList if x > n]'

三。案例:过滤器(不知何故未标记)

filtering = 'list(filter(lambda x: x > n, theList))'

一些准备工作:

import timeit
si = 'theList=range(2000);n=1000;'  # using list(range(2000)) has no effect on the ranking

让我们看看:

timeit.timeit(si+list_comp, number=10000)
Out[21]: 1.3985847820003983
timeit.timeit(si+filtering, number=10000)
Out[22]: 3.315784254024038
timeit.timeit(si+for_case, number=10000)
Out[23]: 2.0093530920275953

所以,至少在我的机器上,列表理解会把它带走,然后是 for -循环,至少在这种情况下 filter 确实是最慢的。