Python max 列表函数

Python max 列表函数用于返回最大值。在本节中,我们将讨论如何使用此列表最大函数,max 函数的语法如下所示。

max(listname)

Python max 列表函数示例

max 函数在列表中返回最大值。下面的代码查找整数中的最大值。

intList = [10, 150, 160, 180, 120, 105]
 
print("The Maximum Value in this List is : ", max(intList))
The Maximum Value in this List is :  180

这是查找最大值的另一个示例。

intLi = [50, 10, 150, 20, 205, 500, 7, 25, 175]
print(intLi)

maximum = max(intLi)

print("\nThe Maximum item = ", maximum)
[50, 10, 150, 20, 205, 500, 7, 25, 175]

The Maximum item =  500

在此示例中,我们声明了一个字符串列表。接下来,我们使用 max 函数返回其中的最大值。在这里,max 函数使用字母顺序查找最大列表值。

请参阅 列表 文章和 方法 文章,以了解有关 Python 中所有这些内容的详细信息。

Fruits = ['Orange', 'Banana', 'Watermelon', 'Kiwi', 'Grape', 'Blackberry']
 
print("The Maximum Value : ", max(Fruits))
The Maximum Value :  Watermelon

Python max 列表示例 3

此列表 max 程序 与第一个示例相同。但是,这一次,我们允许用户输入长度。接下来,我们使用 For Loop 将数字添加到其中。

intList = []

number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, number + 1):
    value = int(input("Please enter the Value of %d Element : " %i))
    intList.append(value)
 
print("The Maximum Value in this List is : ", max(intList))
list max Function Example

此程序允许用户输入自己的字符串或单词,然后查找最大字符串。

strLi = []

number = int(input("Please enter the Total : "))
for i in range(1, number + 1):
    item = input("Please enter the Value of %d Element : " %i)
    strLi.append(item)
 
print("The Maximum Value is : ", max(strLi))
Please enter the Total : 3
Please enter the Value of 1 Element : Kiwi
Please enter the Value of 2 Element : Orange
Please enter the Value of 3 Element : Apple
The Maximum Value is :  Orange

让我对混合列表使用此 max 函数。

MixedLi = ['apple',  1, 5, 'Kiwi', 'Mango']
 
print("The Maximum Value : ", max(MixedLi))

如您所见,它会引发错误,因为它无法对字符串和整数执行 < 运算。

Traceback (most recent call last):
  File "/Users/suresh/Desktop/simple.py", line 3, in <module>
    print("The Maximum Value : ", max(MixedLi))
TypeError: '>' not supported between instances of 'int' and 'str'

这次,我们在嵌套列表上使用了 max 函数。在这里,max 函数使用每个嵌套列表中的第一个值,并从该嵌套列表中返回最大值。

MixedList = [[1, 2], [22, 3], [4, 5]]
 
print(max(MixedList))
[22, 3]