📜  Python - 找出 Matrix 中缺失的列表元素总和的差,反之亦然

📅  最后修改于: 2022-05-13 01:54:19.323000             🧑  作者: Mango

Python - 找出 Matrix 中缺失的列表元素总和的差,反之亦然

给定一个列表和一个 Matrix,任务是编写一个Python程序,该程序可以找到 Matrix 中缺少的列表元素之和的差,反之亦然。

一个更简单的解释是,找到并求和在 Matrix 中找到但不在列表中的所有元素。接下来,查找并求和列表中找到的所有不在矩阵中的元素。执行提取的总和值之间的差异。

方法 1:使用循环from_iterable()



在这种情况下,我们使用循环中的计数器获得列表中存在的元素的列表总和,而不是矩阵,反之亦然,并计算差异。 from_iterable() 用于展平矩阵。

例子:

Python3
# Python3 code to demonstrate working of
# Missing elements difference from Matrix and List
# Using loop
from itertools import chain
  
# initializing list
test_list = [[2, 4, 1], [8, 1, 2], [9, 1, 10], [4, 3, 2]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing target list
tar_list = [2, 3, 10, 7, 5, 4]
  
# flattening Matrix
flat_mat = list(chain.from_iterable(test_list))
  
# getting sum of list elements not in Matrix
list_sum = 0
for ele in tar_list:
    if ele not in flat_mat:
        list_sum += ele
  
# getting sum of Matrix elements not in list
mat_sum = 0
for ele in flat_mat:
    if ele not in tar_list:
        mat_sum += ele
  
# computing difference
res = abs(mat_sum - list_sum)
  
# printing result
print("The computed count : " + str(res))


Python3
# Python3 code to demonstrate working of
# Missing elements difference from Matrix and List
# Using sum() + from_iterable()
from itertools import chain
  
# initializing list
test_list = [[2, 4, 1], [8, 1, 2], [9, 1, 10], [4, 3, 2]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing target list
tar_list = [2, 3, 10, 7, 5, 4]
  
# flattening Matrix
flat_mat = list(chain.from_iterable(test_list))
  
# getting sum of list elements not in Matrix
list_sum = sum([ele for ele in tar_list if ele not in flat_mat])
  
# getting sum of Matrix elements not in list
mat_sum = sum([ele for ele in flat_mat if ele not in tar_list])
  
# computing difference
res = abs(mat_sum - list_sum)
  
# printing result
print("The computed count : " + str(res))


输出:

方法 2:使用sum()from_iterable()

在这里,计算求和的任务是使用 sum() 完成的,其余所有功能都以与上述方法相同的方式执行。



例子:

蟒蛇3

# Python3 code to demonstrate working of
# Missing elements difference from Matrix and List
# Using sum() + from_iterable()
from itertools import chain
  
# initializing list
test_list = [[2, 4, 1], [8, 1, 2], [9, 1, 10], [4, 3, 2]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing target list
tar_list = [2, 3, 10, 7, 5, 4]
  
# flattening Matrix
flat_mat = list(chain.from_iterable(test_list))
  
# getting sum of list elements not in Matrix
list_sum = sum([ele for ele in tar_list if ele not in flat_mat])
  
# getting sum of Matrix elements not in list
mat_sum = sum([ele for ele in flat_mat if ele not in tar_list])
  
# computing difference
res = abs(mat_sum - list_sum)
  
# printing result
print("The computed count : " + str(res))

输出: