Python 列表中最大元素的位置
Python语言包含各种数据结构,其中列表是最常用的。元素被分配在方括号内,并用逗号分隔。可以操作列表以获取不同的方法,并获取最大元素的位置是一种常见方法。一旦在列表数据结构中定义了元素,就无法更改。在本篇文章中,用户将了解如何获取列表中最大元素的位置。
方法
- 方法1 – 使用pandas库
-
方法2 – 使用max和index函数
-
方法3 – 使用lambda函数
方法1:使用Python程序中的pandas模块
通过导入’pandas’模块,可以利用数据帧函数。它以一个输入参数定义。用于获取所需元素的主要函数是max函数及其使用索引方法的位置。
算法
- 步骤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变量中。
-
步骤4 – 然后打印列表中最大元素的位置。
示例
#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]
结论
这篇文章展示了三种方法。这些方法帮助程序员打印列表中所有具有最大值的元素。数据处理是当前技术中最突出的问题之一,打印最大元素的位置是其中的一个基本功能。