Python – 从字典值列表中提取第 K 个索引元素
给定一个以列表为值的字典,提取所有第 K 个索引元素。
Input : {“Gfg” : [4, 7, 5], “Best” : [8, 6, 7], “is” : [9, 3, 8]}, K = 2
Output : [5, 7, 8]
Explanation : The 2nd index elements are 5, 7 and 8 respectively in different keys.
Input : {“Gfg” : [4, 7, 5], “Best” : [8, 6, 7], “is” : [9, 3, 8]}, K = 0
Output : [4, 8, 9]
Explanation : The 0th index elements are 4, 8 and 9 respectively in different keys.
方法 #1:使用列表理解 + values()
上述功能的组合可以用来解决这个问题。在此,使用 values() 提取值,并使用列表推导来构造新列表。
Python3
# Python3 code to demonstrate working of
# Extract Kth index elements from Dictionary Value list
# Using list comprehension + values()
# initializing dictionary
test_dict = {"Gfg" : [4, 7, 5], "Best" : [8, 6, 7], "is" : [9, 3, 8]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 1
# one liner, values() getting all value according to keys
res = [sub[K] for sub in test_dict.values()]
# printing result
print("The extracted values : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Kth index elements from Dictionary Value list
# Using map() + itemgetter()
from operator import itemgetter
# initializing dictionary
test_dict = {"Gfg" : [4, 7, 5], "Best" : [8, 6, 7], "is" : [9, 3, 8]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 1
# map and itemgetter() extracting result
# list() used to convert result from map() to list format
res = list(map(itemgetter(K), test_dict.values()))
# printing result
print("The extracted values : " + str(res))
输出
The original dictionary is : {'Gfg': [4, 7, 5], 'Best': [8, 6, 7], 'is': [9, 3, 8]}
The extracted values : [7, 6, 3]
方法 #2:使用 map() + itemgetter()
上述功能的组合可以用来解决这个问题。在此,我们使用 map() 来扩展获取特定键值的逻辑,而 itemgetter 用于提取特定索引。
Python3
# Python3 code to demonstrate working of
# Extract Kth index elements from Dictionary Value list
# Using map() + itemgetter()
from operator import itemgetter
# initializing dictionary
test_dict = {"Gfg" : [4, 7, 5], "Best" : [8, 6, 7], "is" : [9, 3, 8]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 1
# map and itemgetter() extracting result
# list() used to convert result from map() to list format
res = list(map(itemgetter(K), test_dict.values()))
# printing result
print("The extracted values : " + str(res))
输出
The original dictionary is : {'Gfg': [4, 7, 5], 'Best': [8, 6, 7], 'is': [9, 3, 8]}
The extracted values : [7, 6, 3]