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

2024-10-01 15:40:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

此外,我们有一行for,如下所示

(subList for subList in theList if sublist > n)

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

最后,我们可以使用filter()函数,这是不愉快的使用,至少对我来说。你知道吗

以上方法都是我知道的方法。如果你知道更好的方法,请告诉我。否则,请说明从效率和运行时的角度来看,哪一个是最好的。你知道吗


Tags: 方法in元素列表forlenif错误
2条回答

没有总是正确的答案,也有一些关于处理列表时不同方法的速度的帖子,例如hereherehere。你知道吗

什么是最快的方法可能取决于你的名单很多。 也就是说,让我们看看建议的方法有多快。你知道吗

对于这样的简单比较,可以使用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]'

3岁。大小写:筛选器(以某种方式取消链接)

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确实是最慢的。你知道吗

列表理解版本:

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

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

sublist = ( i for i in the_list if i > n )

相关问题 更多 >

    热门问题