Python – 列表中的嵌套记录列表
有时,在使用Python数据时,我们可能会遇到数据以不同格式传入的问题。在这种情况下,我们可以将数据作为键和值接收到单独的字典中,并且我们需要将值作为具有新键的记录列表。让我们讨论可以执行此任务的某些方式。
方法 #1:使用zip()
+ 循环
上述功能的组合可以用来解决这个问题。在此,我们使用 zip 执行配对,并且手动干预添加密钥以暴力方式完成。
# Python3 code to demonstrate working of
# Nested Records List from Lists
# Using zip() + loop
# initializing lists
test_list1 = ['gfg', 'best']
test_list2 = [[1, 2], [3, 4]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing add_key
add_key = 'id'
# Nested Records List from Lists
# Using zip() + loop
res = dict()
for key, val in zip(test_list1, test_list2):
res[key]=[{add_key : idx} for idx in val]
# printing result
print("The constructed dictionary is : " + str(res))
输出 :
The original list 1 is : [‘gfg’, ‘best’]
The original list 2 is : [[1, 2], [3, 4]]
The constructed dictionary is : {‘gfg’: [{‘id’: 1}, {‘id’: 2}], ‘best’: [{‘id’: 3}, {‘id’: 4}]}
方法 #2:使用字典理解 + zip()
这是执行此任务的另一种方式。这与上述方法类似,只是上述方法的一种替代方案。
# Python3 code to demonstrate working of
# Nested Records List from Lists
# Using dictionary comprehension + zip()
# initializing lists
test_list1 = ['gfg', 'best']
test_list2 = [[1, 2], [3, 4]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing add_key
add_key = 'id'
# Nested Records List from Lists
# Using dictionary comprehension + zip()
res = {key : [{add_key : idx} for idx in val]
for key, val in zip(test_list1, test_list2)}
# printing result
print("The constructed dictionary is : " + str(res))
输出 :
The original list 1 is : [‘gfg’, ‘best’]
The original list 2 is : [[1, 2], [3, 4]]
The constructed dictionary is : {‘gfg’: [{‘id’: 1}, {‘id’: 2}], ‘best’: [{‘id’: 3}, {‘id’: 4}]}