Python - 提取具有复杂数据类型的行
给定 Matrix,提取具有复杂数据类型的行。
例子:
Input : test_list = [[4, 2, 5], [1, [3, 4], 9], [5], [7, (2, 3), 3, 9]]
Output : [[1, [3, 4], 9], [7, (2, 3), 3, 9]]
Explanation : Rows have lists and tuples respectively.
Input : test_list = [[4, 2, [5]], [1, [3, 4], 9], [5], [7, (2, 3), 3, 9]]
Output : [[4, 2, [5]], [1, [3, 4], 9], [7, (2, 3), 3, 9]]
Explanation : Rows have lists and tuples respectively.
方法 #1:使用列表推导+ isinstance() + any()
在此,我们使用 isinstance() 检查行的每个元素是否属于字典、元组、集合或列表数据类型,如果发现任何元素具有该实例,则将该行添加到结果中。
Python3
# Python3 code to demonstrate working of
# Extract rows with Complex data types
# Using list comprehension + isinstance() + any()
# initializing list
test_list = [[4, 2, 5], [1, [3, 4], 9], [5], [7, (2, 3), 3, 9]]
# printing original list
print("The original list is : " + str(test_list))
# checking for any of list, set, tuple or
# dictionary as complex structures
res = [row for row in test_list if any(isinstance(ele, list) or isinstance(ele, tuple)
or isinstance(ele, dict) or isinstance(ele, set) for ele in row)]
# printing result
print("Filtered Rows : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract rows with Complex data types
# Using filter() + lambda + isinstance()
# initializing list
test_list = [[4, 2, 5], [1, [3, 4], 9], [5], [7, (2, 3), 3, 9]]
# printing original list
print("The original list is : " + str(test_list))
# checking for any of list, set, tuple or dictionary as complex structures
res = list(filter(lambda row: any(isinstance(ele, list) or isinstance(ele, tuple)
or isinstance(ele, dict) or isinstance(ele, set) for ele in row), test_list))
# printing result
print("Filtered Rows : " + str(res))
输出:
The original list is : [[4, 2, 5], [1, [3, 4], 9], [5], [7, (2, 3), 3, 9]]
Filtered Rows : [[1, [3, 4], 9], [7, (2, 3), 3, 9]]
方法 #2:使用filter() + lambda + isinstance()
在这里,我们使用 filter 和 lambda 执行过滤任务,使用 isinstance() 检查数据类型。
蟒蛇3
# Python3 code to demonstrate working of
# Extract rows with Complex data types
# Using filter() + lambda + isinstance()
# initializing list
test_list = [[4, 2, 5], [1, [3, 4], 9], [5], [7, (2, 3), 3, 9]]
# printing original list
print("The original list is : " + str(test_list))
# checking for any of list, set, tuple or dictionary as complex structures
res = list(filter(lambda row: any(isinstance(ele, list) or isinstance(ele, tuple)
or isinstance(ele, dict) or isinstance(ele, set) for ele in row), test_list))
# printing result
print("Filtered Rows : " + str(res))
输出:
The original list is : [[4, 2, 5], [1, [3, 4], 9], [5], [7, (2, 3), 3, 9]]
Filtered Rows : [[1, [3, 4], 9], [7, (2, 3), 3, 9]]