从具有不同数据类型的矩阵中提取行的Python程序
给定一个矩阵,任务是编写一个Python程序来提取没有重复数据类型的行。
例子:
Input : test_list = [[4, 3, 1], [“gfg”, 3, {4:2}], [3, 1, “jkl”], [9, (2, 3)]]
Output : [[‘gfg’, 3, {4: 2}], [9, (2, 3)]]
Explanation : [4, 3, 1] are all integers hence omitted. [9, (2, 3)] has integer and tuple, different data types, hence included in results.
Input : test_list = [[4, 3, 1], [“gfg”, 3, {4:2}, 4], [3, 1, “jkl”], [9, (2, 3)]]
Output : [[9, (2, 3)]]
Explanation : [4, 3, 1] are all integers hence omitted. [9, (2, 3)] has integer and tuple, different data types, hence included in results.
方法:使用type() +列表推导
在此,我们使用 type() 来检查行的每个元素的数据类型,如果数据类型重复,则该行不包含在结果中。
Python3
# Python3 code to demonstrate working of
# Distinct Data Type Rows
# Using type() + list comprehension
# initializing list
test_list = [[4, 3, 1], ["gfg", 3, {4: 2}], [3, 1, "jkl"], [9, (2, 3)]]
# printing original list
print("The original list is : " + str(test_list))
res = []
for sub in test_list:
# get Distinct types size
type_size = len(list(set([type(ele) for ele in sub])))
# if equal get result
if len(sub) == type_size:
res.append(sub)
# printing result
print("The Distinct data type rows : " + str(res))
输出:
The original list is : [[4, 3, 1], [‘gfg’, 3, {4: 2}], [3, 1, ‘jkl’], [9, (2, 3)]]
The Distinct data type rows : [[‘gfg’, 3, {4: 2}], [9, (2, 3)]]