📜  Python - 提取特定数据类型行

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

Python - 提取特定数据类型行

给定一个矩阵,提取具有特定数据类型的所有元素的所有行。

方法 #1:使用 isinstance() + all() + 列表理解

在这里,我们使用isinstance() 检查数据类型,all()检查所有属于特定数据类型的元素。

Python3
# Python3 code to demonstrate working of
# Extract Particular data type rows
# Using isinstance() + all() + list comprehension
  
# initializing list
test_list = [[4, 5, "Hello"], [2, 6, 7], ["g", "f", "g"], [9, 10, 11]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing data type
data_type = int
  
# checking data type using isinstance
res = [row for row in test_list if all(
    isinstance(ele, data_type) for ele in row)]
  
# printing result
print("Filtered Rows : " + str(res))


Python3
# Python3 code to demonstrate working of
# Extract Particular data type rows
# Using filter() + lambda + isinstance()
  
# initializing list
test_list = [[4, 5, "Hello"], [2, 6, 7], ["g", "f", "g"], [9, 10, 11]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing data type
data_type = int
  
# checking data type using isinstance
# filter() used to get filter
res = list(filter(lambda row: all(isinstance(ele, data_type)
                                  for ele in row), test_list))
  
# printing result
print("Filtered Rows : " + str(res))


输出:

方法 #2:使用 filter() + lambda + isinstance()

在这种情况下,我们使用filter()lambda 执行过滤任务, isinstance()用于执行类型检查任务,如上述方法。

蟒蛇3

# Python3 code to demonstrate working of
# Extract Particular data type rows
# Using filter() + lambda + isinstance()
  
# initializing list
test_list = [[4, 5, "Hello"], [2, 6, 7], ["g", "f", "g"], [9, 10, 11]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing data type
data_type = int
  
# checking data type using isinstance
# filter() used to get filter
res = list(filter(lambda row: all(isinstance(ele, data_type)
                                  for ele in row), test_list))
  
# printing result
print("Filtered Rows : " + str(res))

输出: