Python - K 列表嵌套字典网格
给定 2 个列表,使用常量列表创建嵌套网格。
Input : test_list1 = [4, 6], test_list2 = [2, 7], K = []
Output : {4: {2: [], 7: []}, 6: {2: [], 7: []}}
Explanation : Nested dictionary initialized with [].
Input : test_list1 = [4], test_list2 = [2], K = [1]
Output : {4: {2: [1]}}
Explanation : Nested dictionary initialized with [1].
方法:使用字典理解
在此,我们使用嵌套字典理解,列表 2 元素的内部一个将列表 1 的每个元素作为键,外部分配列表 1 中的键。
Python3
# Python3 code to demonstrate working of
# K list Nested Dictionary Mesh
# Using * operator
# initializing lists
test_list1 = [4, 6, 8, 7]
test_list2 = [2, 7, 9, 4]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# initializing K
K = [None]
# initializing K list mesh
res = {idx: {sub2: K for sub2 in test_list2} for idx in test_list1}
# printing result
print("Created Mesh : " + str(res))
输出
The original list 1 : [4, 6, 8, 7]
The original list 2 : [2, 7, 9, 4]
Created Mesh : {4: {2: [None], 7: [None], 9: [None], 4: [None]}, 6: {2: [None], 7: [None], 9: [None], 4: [None]}, 8: {2: [None], 7: [None], 9: [None], 4: [None]}, 7: {2: [None], 7: [None], 9: [None], 4: [None]}}