Python - K 差连续元素
给定一个整数元素列表,检查每个元素与连续元素的差是否为 K。
Input : test_list = [5, 6, 3, 2, 5, 3, 4], K = 1
Output : [True, False, True, False, False, True]
Explanation : 5, 6; 3, 2; and 3, 4 have 1 diff. between them.
Input : test_list = [5, 6, 3, 2, 5, 3, 4], K = 2
Output : [False, False, False, False, True, False]
Explanation : Only 5, 3 has 2 diff between it.
方法#1:使用列表推导
这是可以执行此任务的方式之一。在此,我们检查每个元素与下一个元素,如果差异为 K,则我们将其标记为 True,否则标记为 False。
Python3
# Python3 code to demonstrate working of
# K difference Consecutive elements
# Using list comprehension
# initializing list
test_list = [5, 6, 3, 2, 5, 3, 4]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 3
# using list comprehension and abs() to compute result
res = [True if abs(test_list[idx] - test_list[idx + 1]) == K else False
for idx in range(len(test_list) - 1)]
# printing result
print("The difference list result : " + str(res))
Python3
# Python3 code to demonstrate working of
# K difference Consecutive elements
# Using zip() + list comprehension
# initializing list
test_list = [5, 6, 3, 2, 5, 3, 4]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 3
# using list comprehension and abs() to compute result
# zip() used to pair Consecutive elements list
res = [abs(a - b) == K for a, b in zip(test_list, test_list[1:])]
# printing result
print("The difference list result : " + str(res))
输出
The original list : [5, 6, 3, 2, 5, 3, 4]
The difference list result : [False, True, False, True, False, False]
方法 #2:使用 zip() + 列表理解
这是可以执行此任务的另一种方式。在这种情况下,连续列表使用 zip() 配对,计算通过列表理解运行。
Python3
# Python3 code to demonstrate working of
# K difference Consecutive elements
# Using zip() + list comprehension
# initializing list
test_list = [5, 6, 3, 2, 5, 3, 4]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 3
# using list comprehension and abs() to compute result
# zip() used to pair Consecutive elements list
res = [abs(a - b) == K for a, b in zip(test_list, test_list[1:])]
# printing result
print("The difference list result : " + str(res))
输出
The original list : [5, 6, 3, 2, 5, 3, 4]
The difference list result : [False, True, False, True, False, False]