Python – 填补连续记录中的空白
有时,在处理Python记录时,我们可能会遇到记录连续的问题,但有一些记录丢失,需要用任何常数 K 填充。这种问题可以在 Web 开发等领域有应用。让我们讨论一下我们需要执行此任务的某些方式。
Input :
test_list = [(1, 4), (9, 11)]
K = None
Output : [(1, 4), (2, None), (3, None), (4, None), (5, None), (6, None), (7, None), (8, None), (9, 11)]
Input :
test_list = [(1, 4), (2, 11)]
K = None
Output : [(1, 4), (2, 11)]
方法#1:使用循环
这是可以解决此问题的一种方法。在此,我们在每次迭代时检查元素是否存在,如果不存在,则填充所需的值,如果存在,则保留原始值。
# Python3 code to demonstrate working of
# Fill gaps in consecutive Records
# Using loop
# initializing list
test_list = [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K value
K = "New"
# Fill gaps in consecutive Records
# Using loop
res = []
cnt = 0
for i, j in test_list:
if i - cnt > 1:
for k in range(cnt + 1, i):
res.append((k, K))
res.append((i, j))
cnt = i
# printing result
print("The list after filling gaps : " + str(res))
The original list is : [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)]
The list after filling gaps : [(1, 4), (2, ‘New’), (3, 5), (4, 6), (5, ‘New’), (6, ‘New’), (7, 8), (8, ‘New’), (9, 11)]
方法 #2:使用min() + max() + dict()
+ 列表理解
这是可以解决此问题的另一种方式。在此,我们使用 min() 和 max() 检查范围,并使用字典作为获取需要填写的值的容器。
# Python3 code to demonstrate working of
# Fill gaps in consecutive Records
# Using min() + max() + dict() + list comprehension
# initializing list
test_list = [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K value
K = "New"
# Fill gaps in consecutive Records
# Using min() + max() + dict() + list comprehension
test_list = dict(test_list)
mini, maxi = min(test_list), max(test_list)
res = [(idx, test_list.get(idx)) for idx in range(mini, maxi + 1)]
# printing result
print("The list after filling gaps : " + str(res))
The original list is : [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)]
The list after filling gaps : [(1, 4), (2, ‘New’), (3, 5), (4, 6), (5, ‘New’), (6, ‘New’), (7, 8), (8, ‘New’), (9, 11)]