Python|在字典中压缩两个不等长的列表
给定两个可能不等长的列表,任务是压缩字典中的两个列表,使得长度较短的列表会重复。
由于Python中的字典是键值对的无序集合,因此结果将以无序方式打印。
方法 #1:使用itertools()
# Python code to demonstrate
# return the sum of values of a dictionary
# with same keys in the list of dictionary
from itertools import cycle
# Initialising list of dictionary
ini_lis1 = ['a', 'b', 'c', 'd', 'e']
ini_lis2 = [1, 2, 3]
# zipping in cyclic if shorter length
result = dict(zip(ini_lis1, cycle(ini_lis2)))
# printing resultant dictionary
print("resultant dictionary : ", str(result))
输出:
resultant dictionary : {'b': 2, 'd': 1, 'c': 3, 'e': 2, 'a': 1}
方法 #2:使用 dict 理解
# Python code to demonstrate
# return the sum of values of dictionary
# with same keys in list of dictionary
from itertools import cycle
# Initialising list of dictionary
ini_lis1 = ['a', 'b', 'c', 'd', 'e']
ini_lis2 = [1, 2, 3]
# zipping in cyclic if shorter length
result = {v: ini_lis2[i % len(ini_lis2)]
for i, v in enumerate(ini_lis1)}
print("resultant dictionary : ", str(result))
输出:
resultant dictionary : {'d': 1, 'c': 3, 'e': 2, 'b': 2, 'a': 1}
方法 #3:使用 deque()
# Python code to demonstrate
# return the sum of values of dictionary
# with same keys in list of dictionary
from collections import deque
# Initialising list of dictionary
ini_lis1 = ['a', 'b', 'c', 'd', 'e']
ini_lis2 = deque([1, 2, 3])
# zipping in cyclic if shorter length
result = {}
for letter in ini_lis1:
number = ini_lis2.popleft()
result[letter] = number
ini_lis2.append(number)
print("resultant dictionary : ", str(result))
输出:
resultant dictionary : {'c': 3, 'd': 1, 'b': 2, 'e': 2, 'a': 1}