Python - 测试递增字典
给定一个字典,测试它是否在递增,即它的键和值都递增 1。
Input : test_dict = {1:2, 3:4, 5:6, 7:8}
Output : True
Explanation : All keys and values in order differ by 1.
Input : test_dict = {1:2, 3:10, 5:6, 7:8}
Output : False
Explanation : Irregular items.
方法:使用 items() + loop + extend() + list comprehension
在此,第一步是使用items() + list comprehension 和extend()获取字典到列表转换,下一个循环用于测试转换后的列表是否是增量的。
Python3
# Python3 code to demonstrate working of
# Test for Incrementing Dictionary
# Using extend() + list comprehension
# initializing dictionary
test_dict = {1: 2, 3: 4, 5: 6, 7: 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
temp = []
# forming list from dictionary
[temp.extend([key, val]) for key, val in test_dict.items()]
# checking for incrementing elements
res = True
for idx in range(0, len(temp) - 1):
# test for increasing list
if temp[idx + 1] - 1 != temp[idx]:
res = False
# printing result
print("Is dictionary incrementing : " + str(res))
输出:
The original dictionary is : {1: 2, 3: 4, 5: 6, 7: 8}
Is dictionary incrementing : True