Python 用于给键分配最大元素索引
在Python中,元素索引是指一个序列(例如列表或字符串)中元素的位置。它代表了元素的位置,从第一个元素的0开始,每个后续元素增加1。将键分配给最大的元素索引意味着将唯一的标识符或标签与序列中最大可能的索引值关联起来。这种方法可以通过使用分配的键基于它们的位置轻松地访问和检索元素。
示例
假设我们已经输入了一个字典。我们将找到每个键的值中的最大元素,并将其索引分配给键,并使用上述方法打印结果字典。
输入
inputDict = {'hello': [4, 2, 8],
'tutorialspoint': [5, 12, 10],
'python': [9, 3, 7],
'users': [3, 6, 1]}
输出
Resultant dictionary after assigning keys with maximum element index:
{'hello': 2, 'tutorialspoint': 1, 'python': 0, 'users': 1}
在上述输入字典中,键为 hello 的最大元素为 8 ,其索引为 2 。因此,最大元素的索引被赋给键 hello ,该索引为2。同样地,其他元素也是如此,然后打印出结果字典。
hello: 最大元素为8->索引为2
‘tutorialspoint’: 最大元素为12->索引为1
‘python’: 最大元素为9->索引为0
‘users’: 最大元素为6->索引为1
index()函数
index()函数返回提供的值的第一次出现的位置。
语法
list.index(element)
max() 函数
max() 函数返回迭代对象中的最大值/最大数字。
步骤
执行所需任务的算法/步骤如下:
- 创建一个变量来存储输入的字典。
-
打印输入的字典。
-
使用dict()函数创建一个空字典,用于存储结果字典。
-
使用for循环遍历输入字典的键。
-
获取字典键中最大元素的索引,并将该键与最大元素索引存储。
-
在每个键与最大元素索引赋值后,打印结果字典。
示例 1:使用for循环、index()和max()函数
以下程序使用for循环、index()和max()函数,在输入的字典的每个键上分配一个最大元素索引,并返回字典。
示例
# input dictionary
inputDict = {'hello': [4, 2, 8],
'tutorialspoint': [5, 12, 10],
'python': [9, 3, 7],
'users': [3, 6, 1]}
# printing input dictionary
print("Input dictionary:\n", inputDict)
# empty dictionary for storing a resultant dictionary
resultantDict = dict()
# traversing through the keys of the input dictionary
for k in inputDict:
# Getting the maximum element index
# Storing it as a value for the same key
resultantDict[k] = inputDict[k].index(max(inputDict[k]))
# printing resultant dictionary
print("Resultant dictionary after assigning keys with maximum element index:\n", resultantDict)
输出
在执行时,上述程序将产生以下输出
Input dictionary:
{'hello': [4, 2, 8], 'tutorialspoint': [5, 12, 10], 'python': [9, 3, 7], 'users': [3, 6, 1]}
Resultant dictionary after assigning keys with maximum element index:
{'hello': 2, 'tutorialspoint': 1, 'python': 0, 'users': 1}
示例2:使用字典推导、index()和max()函数
在这个例子中,我们使用字典推导,它是上面for循环的快捷版本。
以下程序使用字典推导、index()和max()函数,在为输入字典的每个键分配一个最大元素索引后,返回一个字典。
示例
# input dictionary
inputDict = {'hello': [4, 2, 8],
'tutorialspoint': [5, 12, 10],
'python': [9, 3, 7],
'users': [3, 6, 1]}
# printing input dictionary
print("Input dictionary:\n", inputDict)
# Performing same using dictionary comprehension for concise syntax
resultantDict = {k: inputDict[k].index(max(inputDict[k])) for k in inputDict}
# printing resultant dictionary
print("Resultant dictionary after assigning ks with maximum element index:\n",
resultantDict)
输出
在执行时,上述程序将生成以下输出
Input dictionary:
{'hello': [4, 2, 8], 'tutorialspoint': [5, 12, 10], 'python': [9, 3, 7], 'users': [3, 6, 1]}
Resultant dictionary after assigning ks with maximum element index:
{'hello': 2, 'tutorialspoint': 1, 'python': 0, 'users': 1}
结论
在这篇文章中,我们学习了2种不同的方法来分配具有最大元素索引的键。我们学到了如何找到字典的最高值元素以及其索引。最后,我们学会了如何使用字典推导式来简洁地写出语法。