📜  Python - 将矩阵转换为集合的集合

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

Python - 将矩阵转换为集合的集合

在本文中,任务是编写Python程序将矩阵转换为集合的集合。

例子:

方法 #1:使用set() + freezeset() + 生成器表达式

在此,我们执行迭代直到生成器表达式中的 Matrix 以获取内部集合,并使用 set() 将外部容器转换为集合。内部容器需要是可散列的,因此必须使用frozenset() 来创建。

Python3
# Python3 code to demonstrate working of
# Convert Matrix to Sets of Set
# Using set() + frozenset() + generator expression
  
# initializing list
test_list = [[5, 6, 3], [1, 7, 9], [8, 2, 0]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# frozenset() to get inner elements hashable required for set()
res = set(frozenset(sub) for sub in test_list)
  
# printing result
print("Converted set Matrix : " + str(res))


Python3
# Python3 code to demonstrate working of
# Convert Matrix to Sets of Set
# Using map() + frozenset() + set()
  
# initializing list
test_list = [[5, 6, 3], [1, 7, 9], [8, 2, 0]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# map() to extend logic to inner elements
res = set(map(frozenset, test_list))
  
# printing result
print("Converted set Matrix : " + str(res))


输出:

方法 #2:使用map() + freezeset() + set()

其中,map() 用于扩展将内部容器转换为frozenset() 的逻辑。

蟒蛇3

# Python3 code to demonstrate working of
# Convert Matrix to Sets of Set
# Using map() + frozenset() + set()
  
# initializing list
test_list = [[5, 6, 3], [1, 7, 9], [8, 2, 0]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# map() to extend logic to inner elements
res = set(map(frozenset, test_list))
  
# printing result
print("Converted set Matrix : " + str(res))

输出: