Python – 列表中最大元素的位置
Python 語言包含各種資料結構,其中列表是最常用的資料結構之一。元素在方括號內賦值,並用逗號分隔。列表可以透過不同的方法進行操作,獲取最大元素的位置是一種常見的方法。一旦在列表資料結構(位於方括號內)中定義的元素無法更改。在本文中,使用者將瞭解如何獲取列表中最大元素的位置。
方法
方法 1 - 使用 pandas 庫
方法 2 - 使用 max 和 index 函式
方法 3 - 使用 lambda 函式
方法 1:使用 Python 程式中的 pandas 模組
透過匯入“pandas”模組,可以使用資料幀函式。它使用一個引數作為輸入進行定義。用於獲取所需元素的主要函式是 max 函式及其使用 index 方法的位置。
演算法
步驟 1 - 列表初始化為八個正負值元素
步驟 2 - 要利用資料幀函式,必須匯入必要的模組。
步驟 3 - 然後透過更新後的列表列印 max_val 的內容。
示例
#importing the essential library that is pandas
import pandas as pd
#Creating a list of elements
value1 = [1, 5, 9, -8, 9, 7, 6, 9]
#print function will print the input
print("value1: ", value1)
#data frame method defined with one argument as input
val = pd.DataFrame(value1)
max_val = val[val[0] ==val[0].max()].index.tolist()
#position of the element is returned
print("Positions of the maximum elements are: ", *max_val)
輸出
value1: [1, 5, 9, -8, 9, 7, 6, 9] Positions of the maximum elements are: 2 4 7
方法 2:使用 Python 程式中的 max() 和 index() 函式
要查詢最大元素的位置,主要使用兩個函式。第一個用於獲取最大值,另一個用於使用 index 方法獲取其位置。我們已使用一組整數元素初始化列表資料結構,並使用 max 函式識別列表中的最大元素。
演算法
步驟 1 - 列表初始化為五個正負值元素
步驟 2 -建立一個名為 max_val 的新變數以儲存從 max 函式獲得的結果。
步驟 3 - 類似地,使用 index 函式查詢其位置並將結果儲存在 position 變數中。
步驟 3 - 然後列印列表中最大元素的位置。
示例
#Creating the list of elements
list1 = [6, 10, 2, 30, 15]
#using the max() function to get the maximum element and store it in max_element
max_val = max(list1)
#finding the position using the index value
position = list1.index(max_val)
#print function will return the maximum element and its position
print("Position of maximum element is :", position)
輸出
Position of maximum element is : 3
方法 3:使用 Python 程式中的 lambda 函式
使用函式時需要定義它,但在 lambda 函式的情況下,不需要定義函式,因為它是一個具有關鍵引數的匿名函式。
演算法
列表初始化為八個正負元素。
為了清楚起見,輸入以列表形式列印。
lambda 函式始終與 filter 和 len 函式一起使用
filter 函式將兩個引數作為關鍵引數和範圍。
根據範圍,len 函式將迭代列表。
示例
# create a new list with integer elements
list1 = [3, 5, 80, -9, 80, 70, 60, 80]
#print function will print the input
print("list: ", list1)
max_val = list(filter(lambda a:list1[a] == max(list1), range(len(list1))))
#position of the maximum element
print("Positions of the maximum element is : ", max_val)
輸出
list: [3, 5, 80, -9, 80, 70, 60, 80] Positions of the maximum element is : [2, 4, 7]
結論
本文演示了三種方法。這些方法幫助程式設計師列印列表中所有具有最大值的元素。資料處理是當前技術中最突出的內容之一,列印最大元素的位置是基本功能之一。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP