Python – 替代列表元素作为键值对
给定一个列表,通过将替代元素映射为键值对将其转换为字典。
Input : test_list = [2, 3, 5, 6, 7, 8]
Output : {3: 6, 6: 8, 2: 5, 5: 7}
Explanation : Alternate elements mapped to get key-value pairs. 3 -> 6 [ alternate]
Input : test_list = [2, 3, 5, 6]
Output : {3: 6, 2: 5}
Explanation : Alternate elements mapped to get key-value pairs. 3 -> 6 [ alternate]
方法#1:使用循环
这是可以执行此任务的方法之一。在此,我们迭代两次以获取两个替代元素以获得所需的所有替代键值字典。
Python3
# Python3 code to demonstrate working of
# Alternate Elements Dictionary
# Using loop
# initializing list
test_list = [2, 3, 5, 6, 7, 8, 9, 10]
# printing original list
print("The original list is : " + str(test_list))
res = dict()
# pairing first set of Alternate elements
for idx in range(len(test_list) - 2):
if idx % 2:
res[test_list[idx]] = test_list[idx + 2]
# pairing other set
for idx in range(len(test_list) - 2):
if not idx % 2:
res[test_list[idx]] = test_list[idx + 2]
# printing result
print("The extracted dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Alternate Elements Dictionary
# Using dictionary comprehension + list slicing
# initializing list
test_list = [2, 3, 5, 6, 7, 8, 9, 10]
# printing original list
print("The original list is : " + str(test_list))
# extracting lists
list1 = test_list[1::2]
list2 = test_list[::2]
# constructing pairs using dictionary comprehension
res = {list1[idx] : list1[idx + 1] for idx in range(len(list1) - 1)}
res.update({list2[idx] : list2[idx + 1] for idx in range(len(list2) - 1)})
# printing result
print("The extracted dictionary : " + str(res))
输出
The original list is : [2, 3, 5, 6, 7, 8, 9, 10]
The extracted dictionary : {3: 6, 6: 8, 8: 10, 2: 5, 5: 7, 7: 9}
方法#2:使用字典理解+列表切片
这是可以执行此任务的另一种方式。在这里,我们切出两个替代元素列表并使用字典理解进行配对。
蟒蛇3
# Python3 code to demonstrate working of
# Alternate Elements Dictionary
# Using dictionary comprehension + list slicing
# initializing list
test_list = [2, 3, 5, 6, 7, 8, 9, 10]
# printing original list
print("The original list is : " + str(test_list))
# extracting lists
list1 = test_list[1::2]
list2 = test_list[::2]
# constructing pairs using dictionary comprehension
res = {list1[idx] : list1[idx + 1] for idx in range(len(list1) - 1)}
res.update({list2[idx] : list2[idx + 1] for idx in range(len(list2) - 1)})
# printing result
print("The extracted dictionary : " + str(res))
输出
The original list is : [2, 3, 5, 6, 7, 8, 9, 10]
The extracted dictionary : {3: 6, 6: 8, 8: 10, 2: 5, 5: 7, 7: 9}