📜  Python – 标记矩阵中的无元素行

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

Python – 标记矩阵中的无元素行

给定一个矩阵,对于包含无值的行返回 True,否则返回 False。

方法#1:使用列表推导

在此,我们对每一行进行迭代并使用 in运算符来检查其中的 None。如果找到,则返回 True,否则返回 False。

Python3
# Python3 code to demonstrate working of 
# Flag None Element Rows in Matrix
# Using list comprehension
  
# initializing list
test_list = [[2, 4, None, 3], [3, 4, 1, None], [2, 4, 7, 4], [2, 8]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# in operator to check None value 
# True if any None is found 
res = [True if None in sub else False for sub in test_list]
  
# printing result 
print("None Flagged List : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Flag None Element Rows in Matrix
# Using all() + list comprehension
  
# initializing list
test_list = [[2, 4, None, 3], [3, 4, 1, None], [2, 4, 7, 4], [2, 8]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# all() checks for all non none values  
res = [False if all(sub) else True for sub in test_list]
  
# printing result 
print("None Flagged List : " + str(res))


输出
The original list is : [[2, 4, None, 3], [3, 4, 1, None], [2, 4, 7, 4], [2, 8]]
None Flagged List : [True, True, False, False]

方法 #2:使用 all() + 列表推导

在此,我们使用 all() 检查所有值是否为 True,如果是,则其未标记为 True,并且列表推导用于检查每一行。

Python3

# Python3 code to demonstrate working of 
# Flag None Element Rows in Matrix
# Using all() + list comprehension
  
# initializing list
test_list = [[2, 4, None, 3], [3, 4, 1, None], [2, 4, 7, 4], [2, 8]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# all() checks for all non none values  
res = [False if all(sub) else True for sub in test_list]
  
# printing result 
print("None Flagged List : " + str(res))
输出
The original list is : [[2, 4, None, 3], [3, 4, 1, None], [2, 4, 7, 4], [2, 8]]
None Flagged List : [True, True, False, False]