Python - 矩阵中的元素分组列表
当需要将矩阵中的元素进行分组时,可以使用简单的迭代,“pop”方法,列表解析和“append”方法。
示例
下面演示了上述内容 −
my_list = [[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]
print("The list is :")
print(my_list)
check_list = [14, 12, 41, 62]
print("The list is :")
print(check_list)
my_result = []
while my_list:
sub_list_1 = my_list.pop()
sub_list_2 = [element for element in check_list if element not in sub_list_1]
try:
my_list.remove(sub_list_2)
my_result.append([sub_list_1, sub_list_2])
except ValueError:
my_result.append(sub_list_1)
print("The result is :")
print(my_result)输出
The list is : [[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]] The list is : [14, 12, 41, 62] The result is : [[[41, 14], [12, 62]], [78, 87], [51, 23], [14, 62]]
说明
定义了一个整数列表并将它显示在控制台上。
定义另一个整数列表并将它显示在控制台上。
定义一个空列表。
使用一个简单的迭代,并使用“pop”方法弹出最上面的元素。
将其赋值给变量“sub_list_1”。
使用列表解析来迭代第二个列表,并检查元素是否不在“sub_list_1”中。
使用“try”和“except”块将特定元素附加到空列表。
此列表将显示为控制台上的输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP