提取具有不同資料型別的矩陣中的行的 Python 程式


當需要從具有不同資料型別的矩陣中提取行時,對其進行迭代並使用“集合”來獲得不同的型別。

示例

以下是同樣的演示

my_list = [[4, 2, 6], ["python", 2, {6: 2}], [3, 1, "fun"], [9, (4, 3)]]

print("The list is :")
print(my_list)
my_result = []
for sub in my_list:

   type_size = len(list(set([type(ele) for ele in sub])))

   if len(sub) == type_size:
      my_result.append(sub)

print("The resultant distinct data type rows are :")
print(my_result)

輸出

The list is :
[[4, 2, 6], ['python', 2, {6: 2}], [3, 1, 'fun'], [9, (4, 3)]]
The resultant distinct data type rows are :
[['python', 2, {6: 2}], [9, (4, 3)]]

解釋

  • 定義了一個不同資料型別的列表並在控制檯上顯示

  • 定義一個空列表。

  • 對原始列表進行迭代,並確定每個元素的型別。

  • 將其轉換為集合型別,然後轉換為列表。

  • 確定其大小,並將其與特定大小進行比較。

  • 如果它們匹配,則追加到空列表中。

  • 這在控制檯上顯示為輸出。

更新於:20-9-2021

118 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.