Python – 矩阵中的关键列字典
给定一个矩阵和键列表,将每列值映射到自定义列表键。
Input : test_list1 = [[4, 6], [8, 6]], test_list2 = [“Gfg”, “Best”]
Output : {‘Gfg’: [4, 8], ‘Best’: [6, 6]}
Explanation : Column wise, Key values assignment.
Input : test_list1 = [[4], [6]], test_list2 = [“Gfg”]
Output : {‘Gfg’: [4, 6]}
Explanation : Column wise, Key values assignment, just single element list.
方法#1:使用列表理解+字典理解
上述功能的组合可以用来解决这个问题。在此,我们使用列表推导执行提取列值的任务,然后使用字典推导来形成具有列表键的字典。
Python3
# Python3 code to demonstrate working of
# Key Columns Dictionary from Matrix
# Using list comprehension + dictionary comprehension
# initializing lists
test_list1 = [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
test_list2 = ["Gfg", "is", "Best"]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using enumerate to get column numbers
# dictionary comprehension to compile result
res = {key: [sub[idx] for sub in test_list1] for idx, key in enumerate(test_list2)}
# printing result
print("The paired dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Key Columns Dictionary from Matrix
# Using zip() + dict()
# initializing lists
test_list1 = [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
test_list2 = ["Gfg", "is", "Best"]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# zip() used to map keys with values and return tuples
# as result
# * operator used to perform unpacking
res = dict(zip(test_list2, zip(*test_list1)))
# printing result
print("The paired dictionary : " + str(res))
输出
The original list 1 : [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
The original list 2 : ['Gfg', 'is', 'Best']
The paired dictionary : {'Gfg': [4, 8, 8], 'is': [6, 4, 6], 'Best': [8, 2, 3]}
方法#2:使用 zip() + dict()
这是可以执行此任务的另一种方式。在此,我们使用 zip() 连接键值对,并使用 dict() 将结果转换为字典。不同之处在于它生成元组而不是列表作为映射值。
Python3
# Python3 code to demonstrate working of
# Key Columns Dictionary from Matrix
# Using zip() + dict()
# initializing lists
test_list1 = [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
test_list2 = ["Gfg", "is", "Best"]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# zip() used to map keys with values and return tuples
# as result
# * operator used to perform unpacking
res = dict(zip(test_list2, zip(*test_list1)))
# printing result
print("The paired dictionary : " + str(res))
输出
The original list 1 : [[4, 6, 8], [8, 4, 2], [8, 6, 3]]
The original list 2 : ['Gfg', 'is', 'Best']
The paired dictionary : {'Gfg': (4, 8, 8), 'is': (6, 4, 6), 'Best': (8, 2, 3)}