简体   繁体   English

我不明白 python 中的这个 max 函数

[英]I don't understand this max function in python

I am new to programming and python.我是编程和 python 的新手。 I was playing around with this max function and I don't understand why it is not returning the maximum value when actually it should我在玩这个 max 函数,但我不明白为什么它实际上应该返回最大值

n = [11,3,9]
first_last = [n[1],n[-1]]
largest = max(first_last)
print(largest)

The result is 9 instead of 11 but why?结果是 9 而不是 11 但为什么呢?

Indexing in python starts from 0. So do python中的索引从0开始。所以做

list = [11,3,9]
print(max(list[0],list[-1])

Your Code:您的代码:

n = [11,3,9] first_last = [n[1],n[-1]] largest = max(first_last) print(largest)

Indexing in python starts from 0. While negative sequence indices (-1, -2, -3,.....) helps in accessing array from the last element. python 中的索引从 0 开始。而负序列索引 (-1, -2, -3,.....) 有助于从最后一个元素访问数组。

So, your n[1]=3 and n[-1]=9.所以,你的 n[1]=3 和 n[-1]=9。 This makes first_last = [3, 9].这使得 first_last = [3, 9]。 So when you passed first_last in the max function, it gave you the maximum value among the elements of first_last which is 9.因此,当您在 max 函数中传递 first_last 时,它为您提供了 first_last 元素中的最大值,即 9。

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

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