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”塊將特定元素附加到空列表。

  • 此列表將顯示為控制檯上的輸出。

更新於: 08-Sep-2021

234 次瀏覽

開啟 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.