用特定的对和过滤行的Python程序
给定 Matrix,以下程序显示如何提取具有一对的所有行,使得它们的总和等于特定数字,此处表示为 K。
Input : test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]], k = 8
Output : [[1, 5, 3, 6], [6, 9, 3, 2]]
Explanation : 5 + 3 = 8 and 6 + 2 = 8.
Input : test_list = [[1, 5, 4, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 7]], k = 8
Output : []
Explanation : No list with 8 as pair summation.
方法 1:使用循环和列表理解
在此,我们执行使用外部函数获取总和等于给定值的所有对的任务,并使用列表理解完成列表过滤。
Python3
# get pair sum
def pair_sum(x, k):
# checking pair sum
for idx in range(len(x)):
for ix in range(idx + 1, len(x)):
if x[idx] + x[ix] == k:
return True
return False
# initializing list
test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
k = 8
# checking for pair sum
res = [ele for ele in test_list if pair_sum(ele, k)]
# printing result
print("Filtered Rows : " + str(res))
Python3
# get pair sum
def pair_sum(x, k):
# checking pair sum
for idx in range(len(x)):
for ix in range(idx + 1, len(x)):
if x[idx] + x[ix] == k:
return True
return False
# initializing list
test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
k = 8
# checking for pair sum
# filtering using filter() and lambda
res = list(filter(lambda ele: pair_sum(ele, k), test_list))
# printing result
print("Filtered Rows : " + str(res))
输出:
The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
Filtered Rows : [[1, 5, 3, 6], [6, 9, 3, 2]]
方法 2:使用filter()和lambda
在这里,我们使用 filter() 和 lambda函数执行过滤任务。
蟒蛇3
# get pair sum
def pair_sum(x, k):
# checking pair sum
for idx in range(len(x)):
for ix in range(idx + 1, len(x)):
if x[idx] + x[ix] == k:
return True
return False
# initializing list
test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
k = 8
# checking for pair sum
# filtering using filter() and lambda
res = list(filter(lambda ele: pair_sum(ele, k), test_list))
# printing result
print("Filtered Rows : " + str(res))
输出:
The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
Filtered Rows : [[1, 5, 3, 6], [6, 9, 3, 2]]