Python - 将元组列表转换为具有给定起始值的键的字典
给定一个元组列表,下面的文章重点介绍如何将其转换为字典,键从指定的起始值开始。这个起始值只是为了提供一个良好的开端,下一个键将增加其前一个键的值。
Input : test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)], start = 4
Output : {4: (4, 5), 5: (1, 3), 6: (9, 4), 7: (8, 2), 8: (10, 1)}
Explanation : Tuples indexed starting key count from 4.
Input : test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)], start = 6
Output : {6: (4, 5), 7: (1, 3), 8: (9, 4), 9: (8, 2), 10: (10, 1)}
Explanation : Tuples indexed starting key count from 6.
方法一:使用循环
在这里,我们通过迭代每个元组并添加其位置索引来构建字典,从开始,作为字典中的键 - 值对。
Python3
# initializing list
test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)]
# printing original list
print("The original list is : " + str(test_list))
# initializing start
start = 4
res = dict()
for sub in test_list:
# assigning positional index
res[start] = sub
start += 1
# printing result
print("Constructed dictionary : " + str(res))
Python3
# initializing list
test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)]
# printing original list
print("The original list is : " + str(test_list))
# initializing start
start = 4
res = dict(enumerate(test_list, start=start))
# printing result
print("Constructed dictionary : " + str(res))
输出:
The original list is : [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)]
Constructed dictionary : {4: (4, 5), 5: (1, 3), 6: (9, 4), 7: (8, 2), 8: (10, 1)}
方法 2:使用dict()和enumerate()
在这里,我们使用 dict() 将元组列表转换为字典,并使用 enumerate() 提供索引。
蟒蛇3
# initializing list
test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)]
# printing original list
print("The original list is : " + str(test_list))
# initializing start
start = 4
res = dict(enumerate(test_list, start=start))
# printing result
print("Constructed dictionary : " + str(res))
输出:
The original list is : [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)]
Constructed dictionary : {4: (4, 5), 5: (1, 3), 6: (9, 4), 7: (8, 2), 8: (10, 1)}