Python - 从矩阵中过滤表示字典键的不可变行
给定矩阵,提取所有具有元素的行,这些元素具有可以表示为字典键的所有元素,即不可变的。
Input : test_list = [[4, 5, [2, 3, 2]], [“gfg”, 1, (4, 4)], [{5:4}, 3, “good”], [True, “best”]]
Output : [[‘gfg’, 1, (4, 4)], [True, ‘best’]]
Explanation : All elements in tuples are immutable.
Input : test_list = [[4, 5, [2, 3, 2]], [“gfg”, 1, (4, 4), [3, 2]], [{5:4}, 3, “good”], [True, “best”]]
Output : [[True, ‘best’]]
Explanation : All elements in tuples are immutable.
方法 #1:使用 all() + isinstance()
在此,我们检查所有元素是否属于不可变数据类型的实例,对所有元素返回True的行进行过滤。
Python3
# Python3 code to demonstrate working of
# Filter Dictionary Key Possible Element rows
# Using all() + isinstance()
# initializing list
test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [
True, "best"]]
# printing original list
print("The original list is : " + str(test_list))
# checking for each immutable data type
res = [row for row in test_list if all(isinstance(ele, int) or isinstance(ele, bool)
or isinstance(ele, float) or isinstance(ele, tuple)
or isinstance(ele, str) for ele in row)]
# printing result
print("Filtered rows : " + str(res))
Python3
# Python3 code to demonstrate working of
# Filter Dictionary Key Possible Element rows
# Using filter() + lambda + isinstance() + all()
# initializing list
test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [
True, "best"]]
# printing original list
print("The original list is : " + str(test_list))
# checking for each immutable data type
# filtering using filter()
res = list(filter(lambda row: all(isinstance(ele, int) or isinstance(ele, bool)
or isinstance(ele, float) or isinstance(ele, tuple)
or isinstance(ele, str) for ele in row), test_list))
# printing result
print("Filtered rows : " + str(res))
输出:
The original list is : [[4, 5, [2, 3, 2]], [‘gfg’, 1, (4, 4)], [{5: 4}, 3, ‘good’], [True, ‘best’]]
Filtered rows : [[‘gfg’, 1, (4, 4)], [True, ‘best’]]
方法 #2:使用 filter() + lambda + isinstance() + all()
在此,我们使用filter() + lambda函数执行过滤任务,其余所有功能均按上述方法执行。
蟒蛇3
# Python3 code to demonstrate working of
# Filter Dictionary Key Possible Element rows
# Using filter() + lambda + isinstance() + all()
# initializing list
test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [
True, "best"]]
# printing original list
print("The original list is : " + str(test_list))
# checking for each immutable data type
# filtering using filter()
res = list(filter(lambda row: all(isinstance(ele, int) or isinstance(ele, bool)
or isinstance(ele, float) or isinstance(ele, tuple)
or isinstance(ele, str) for ele in row), test_list))
# printing result
print("Filtered rows : " + str(res))
输出:
The original list is : [[4, 5, [2, 3, 2]], [‘gfg’, 1, (4, 4)], [{5: 4}, 3, ‘good’], [True, ‘best’]]
Filtered rows : [[‘gfg’, 1, (4, 4)], [True, ‘best’]]