简体   繁体   English

什么是计算列表最大值的更有效方法?

[英]What is the more efficient way to compute the max of a list?

I've been messing with Python a little bit and realized that I've been computing the max of a list the wrong way all this time ! 我一直在弄乱Python,并意识到我一直都在用错误的方式计算列表的最大值!

This piece of code (which I've been using up to now :/) 这段代码(我到目前为止一直在使用:/)

mylist = [randint(0,1000) for _ in range(10**6)]
mymax = mylist[0]
for elm in mylist:
    mymax = max(elm, mymax)

takes 0.214785s to run, whereas this one 需要0.214785s来运行,而这一步

mymax = max(*mylist)

only 0.049693s ! 只有0.049693s!

The first one is more than four times slower. 第一个速度慢了四倍以上。 So I was wondering : Is there an even better way to compute the max of a list in python? 所以我想知道:是否有更好的方法来计算python中列表的最大值?

even better way ... 更好的方法...

I have no idea if it's more performant, but you technically don't need to unpack the list: 我不知道它是否更具性能,但是从技术上讲,您不需要打开列表:

mymax = max(mylist)

In your Python interpreter, type help(max) , you will get: 在您的Python解释器中,键入help(max) ,您将获得:

Help on built-in function max in module __builtin__:

max(...)
    max(iterable[, key=func]) -> value
    max(a, b, c, ...[, key=func]) -> value

    With a single iterable argument, return its largest item.
    With two or more arguments, return the largest argument.

max is written in C , so it should already fast enough, your issue is using it in a not very right way. max是用C编写的,因此它应该已经足够快了,您的问题是以不太正确的方式使用它。

The simplest and best way to find max from the list is: 从列表中找到最大值的最简单最佳方法是:

max(mylist)

You don't need to unpack the list. 您无需打开列表包装。

您应该简单地写:

mymax = max(mylist)

Your code should just be these two lines. 您的代码应该只是这两行。

mylist = [random.randint(0,1000) for _ in range(10**6)]
max_elm = max(mylist)

You do not have to trace through every element of the list. 您不必遍历列表的每个元素。 List has many associated functions with it. 列表具有许多关联功能。 Use them. 使用它们。 It would take it about 0.015854835510253906 seconds. 大约需要0.015854835510253906秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM