Python从矩阵过滤代表字典键的不可变行

本文概述

  • Python3
  • Python3
给定矩阵, 提取所有包含元素的行, 这些行具有可以表示为字典键(即不可变)的所有元素。
【Python从矩阵过滤代表字典键的不可变行】输入:test_list = [[4, 5, [2, 3, 2]], [“gfg”, 1, (4, 4)], [{5:4}, 3, “good”], [True, “best”]]
输出:[[‘ gfg’ , 1, (4, 4)], [True, ‘ best’ ]]
说明:元组中的所有元素都是不可变的。
输入:test_list = [[4, 5, [2, 3, 2]], [” gfg” , 1, (4, 4), [3, 2]], [{5:4}, 3, “ 好” ], [True, “ good” ]]
输出:[[True, ‘ best’ ]]
说明:元组中的所有元素都是不可变的。
方法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))

输出如下:
原始列表是:[[4, 5, [2, 3, 2]], [‘ gfg’ , 1, (4, 4)], [{5:4}, 3, ‘ good’ ], [True , ‘ best’ ]]
过滤的行:[[‘ gfg’ , 1, (4, 4)], [True, ‘ good’ ]]
方法2:使用filter()+ lambda + isinstance()+ all()
在此, 我们使用filter()+ lambda功能, 其余所有功能均按上述方法执行。
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))

输出如下:
原始列表是:[[4, 5, [2, 3, 2]], [‘ gfg’ , 1, (4, 4)], [{5:4}, 3, ‘ good’ ], [True , ‘ best’ ]]
过滤的行:[[‘ gfg’ , 1, (4, 4)], [True, ‘ good’ ]]
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

    推荐阅读