Python – 将列表转换为索引和值字典
给定一个列表,将其转换为字典,索引和值具有单独的键。
Input : test_list = [3, 5, 7, 8, 2, 4, 9], idx, val = “1”, “2”
Output : {‘1’: [0, 1, 2, 3, 4, 5, 6], ‘2’: [3, 5, 7, 8, 2, 4, 9]}
Explanation : Index and values mapped at similar index in diff. keys., as “1” and “2”.
Input : test_list = [3, 5, 7], idx, val = “1”, “2”
Output : {‘1’: [0, 1, 2], ‘2’: [3, 5, 7]}
Explanation : Index and values mapped at similar index in diff. keys., as “1” and “2”.
方法:使用循环+枚举()
在此,我们使用 enumerate() 迭代列表元素以获取索引和值,并相应地将值和索引附加到单独的字典中。
Python3
# Python3 code to demonstrate working of
# Convert List to Index and Value dictionary
# Using loop + enumerate()
# initializing list
test_list = [3, 5, 7, 8, 2, 4, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing keys for index and vals
idx, val = "indx", "vals"
# initializing empty mesh
res = {idx : [], val : []}
for id, vl in enumerate(test_list):
res[idx].append(id)
res[val].append(vl)
# printing results
print("Constructed dictionary : " + str(res))
输出
The original list is : [3, 5, 7, 8, 2, 4, 9]
Constructed dictionary : {'indx': [0, 1, 2, 3, 4, 5, 6], 'vals': [3, 5, 7, 8, 2, 4, 9]}