Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 优化代码运行时间[以下代码之间的差异]_Python_Python 3.x - Fatal编程技术网

Python 优化代码运行时间[以下代码之间的差异]

Python 优化代码运行时间[以下代码之间的差异],python,python-3.x,Python,Python 3.x,这是两个代码,谁能告诉我为什么第二个需要更多时间运行 #1 ar = [9547948, 8558390, 9999933, 5148263, 5764559, 906438, 9296778, 1156268] count=0 big = max(ar) for i in range(len(ar)): if(ar[i]==big): count+=1 print(count) #2 ar = [9547948, 8558390, 9999933, 5148

这是两个代码,谁能告诉我为什么第二个需要更多时间运行

#1
ar = [9547948, 8558390, 9999933, 5148263, 5764559, 906438, 9296778, 1156268]
 count=0
 big = max(ar)
 for i in range(len(ar)):
    if(ar[i]==big):
        count+=1
 print(count)


#2
ar = [9547948, 8558390, 9999933, 5148263, 5764559, 906438, 9296778, 1156268]
list = [i for i in ar if i == max(ar)]
return len(list)

在第二个列表中,if子句针对每个候选项进行求值,因此每次都对max进行求值

在第一个循环中,在循环开始之前,计算一次最大值。通过以相同的方式预先评估最大值,您可能会从列表理解中获得类似的性能:

maxiest = max(ar)
list = [i for i in ar if i == maxiest]
此外,您并没有在第一个列表中创建新的列表,而是在计算与最大列表匹配的项目。这也可能有影响,但你必须做一些测量来确定

当然,如果你只是想知道这两种算法之间的区别,那很有希望回答你的问题。但是,您应该知道,max本身通常会传递数据,然后您的搜索会再次传递数据。有一种方法只需通过一次,类似于:

def countLargest(collection):
    # Just return zero for empty list.

    if len(collection) == 0: return 0

    # Setup so first item is largest with count one.

    count = 0
    largest = collection[0]

    # Process every item.

    for item in collection:
        if item > largest:
            # Larger: Replace with count one.

            largest = item
            count = 1
        elif item == largest:
            # Equal: increase count.

            count += 1

    return count
请记住,您应该根据可能的数据集检查这是否更快,优化的口号是“测量”,而不是猜测


而且,老实说,除非你的数据集变得非常大,或者你每秒需要做很多次,否则这不会有多大的区别。这当然不会对您的八元素集合产生任何真正的影响。有时,优化可读性比优化性能更好。

因为您需要重新计算列表中每个循环的maxar。这使得您的代码也在**2上运行,所以当ar变大时,情况会变得更糟。countmaxar@Peter,这可能是一个更好的方法,但它并没有真正回答为什么第二个比第一个慢的问题。但我想这就是为什么你把它作为一个评论而不是一个回答,所以我现在闭嘴:-@paxdiablo你是对的,我们应该解决OP的误解。不过还有更好的算法。我们都在使用两个线性搜索,而实际上只需要一个过程。还有其他的吗?