簡體   English   中英

我不明白 python 中的這個 max 函數

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

我是編程和 python 的新手。 我在玩這個 max 函數,但我不明白為什么它實際上應該返回最大值

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

結果是 9 而不是 11 但為什么呢?

python中的索引從0開始。所以做

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

您的代碼:

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

python 中的索引從 0 開始。而負序列索引 (-1, -2, -3,.....) 有助於從最后一個元素訪問數組。

所以,你的 n[1]=3 和 n[-1]=9。 這使得 first_last = [3, 9]。 因此,當您在 max 函數中傳遞 first_last 時,它為您提供了 first_last 元素中的最大值,即 9。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM