📜  Python - 使用最大元素索引分配键

📅  最后修改于: 2022-05-13 01:54:54.117000             🧑  作者: Mango

Python - 使用最大元素索引分配键

给定带有值列表的字典,任务是编写一个Python程序,为每个键分配值列表中最大值的索引。

例子:

方法 #1:使用max() + loop + index()

在这里,我们使用 max() 和 index() 从值列表中获取最大元素的索引。循环用于字典中键的迭代任务。

Python3
# Python3 code to demonstrate working of
# Assign keys with Maximum element index
# Using max() + index() + loop
  
# initializing dictionary
test_dict = {"gfg": [5, 3, 6, 3], "is": [1, 7, 5, 3], "best": [9, 1, 3, 5]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
res = dict()
for key in test_dict:
  
    # using index() to get required value
    res[key] = test_dict[key].index(max(test_dict[key]))
  
# printing result
print("The maximum index assigned dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of
# Assign keys with Maximum element index
# Using dictionary comprehension + max() + index()
  
# initializing dictionary
test_dict = {"gfg": [5, 3, 6, 3], "is": [1, 7, 5, 3], "best": [9, 1, 3, 5]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# using dictionary comprehension as one liner alternative
res = {key: test_dict[key].index(max(test_dict[key])) for key in test_dict}
  
# printing result
print("The maximum index assigned dictionary : " + str(res))


输出:

方法 #2:使用字典理解 + max() + index()

在此,我们使用上述方法的字典理解速记变体来执行获取结果的任务。

蟒蛇3

# Python3 code to demonstrate working of
# Assign keys with Maximum element index
# Using dictionary comprehension + max() + index()
  
# initializing dictionary
test_dict = {"gfg": [5, 3, 6, 3], "is": [1, 7, 5, 3], "best": [9, 1, 3, 5]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# using dictionary comprehension as one liner alternative
res = {key: test_dict[key].index(max(test_dict[key])) for key in test_dict}
  
# printing result
print("The maximum index assigned dictionary : " + str(res))

输出: