我们经常使用列表来存储数字。在这篇文章中,我们将讨论在Python中寻找列表中最大元素的不同方法。
使用 Python 中的 sort() 方法找到列表中最大的元素
如果一个列表被排序,最大的元素位于列表的末尾,我们可以使用语法list_name[-1] 访问它。如果列表是按降序排序的,列表中最大的元素位于第一个位置,即索引0。我们可以使用语法list_name[0] 来访问它。
当一个列表没有排序时,寻找最大的数字是一个稍微不同的任务。在这种情况下,我们可以先对列表进行排序,然后访问排序后的列表的最后一个元素。或者,我们可以检查列表中的每个元素,然后找到列表中最大的元素。
为了通过对列表进行排序找到最大的元素,我们可以使用sort() 方法。sort() 方法,当在一个列表上调用时,将列表按升序进行排序。排序后,我们可以从索引-1得到列表中最大的元素,如下所示。
myList = [1, 23, 12, 45, 67, 344, 26]
print("The given list is:")
print(myList)
myList.sort()
print("The maximum element in the list is:", myList[-1])
输出
The given list is:
[1, 23, 12, 45, 67, 344, 26]
The maximum element in the list is: 344
使用sorted()方法寻找列表中最大的元素
如果你不允许对原始列表进行排序,你可以使用sorted() 函数对列表进行排序。sorted() 函数将一个列表作为输入参数,并返回一个排序的列表。得到排序后的列表后,我们可以在索引-1处找到列表中最大的元素,方法如下。
myList = [1, 23, 12, 45, 67, 344, 26]
print("The given list is:")
print(myList)
newList = sorted(myList)
print("The maximum element in the list is:", newList[-1])
输出
The given list is:
[1, 23, 12, 45, 67, 344, 26]
The maximum element in the list is: 344
在 Python 中使用临时变量找到列表中最大的元素
对一个列表进行排序需要O(n*log(n)) 时间,其中 n 是列表中元素的数量。对于较大的列表,在我们获得最大的元素之前,可能需要很长的时间对列表进行排序。使用另一种方法,我们可以在O(n) 时间内找到列表中的最大元素。
在这种方法中,我们将创建一个变量myVar ,并用列表中的第一个元素初始化它。现在,我们将认为myVar 有最大的元素。之后,我们将把myVar 与列表中的每个元素进行比较。如果发现任何元素大于myVar ,我们将用当前值更新myVar 。遍历整个列表后,我们将在myVar 变量中得到列表中最大的元素。你可以在下面的例子中观察到这一点。
myList = [1, 23, 12, 45, 67, 344, 26]
print("The given list is:")
print(myList)
myVar = myList[0]
for element in myList:
if element > myVar:
myVar = element
print("The maximum element in the list is:", myVar)
输出
The given list is:
[1, 23, 12, 45, 67, 344, 26]
The maximum element in the list is: 344
使用 Python 中的 max() 函数获得列表中最大的元素
与上述方法相反,你可以直接使用max() 函数来找到列表中最大的元素。max() 函数将列表作为输入参数,并返回列表的最大元素,如下图所示。
myList = [1, 23, 12, 45, 67, 344, 26]
print("The given list is:")
print(myList)
myVar = max(myList)
print("The maximum element in the list is:", myVar)
输出
The given list is:
[1, 23, 12, 45, 67, 344, 26]
The maximum element in the list is: 344
结论
在这篇文章中,我们讨论了在 python 中寻找列表中最大元素的各种方法。