用於移除具有自定義列表元素行的 Python 程式


在需要移除具有自定義列表元素的行時,會用到列表解析和“any”運算子。

示例

以下是相同示例的演示

my_list = [[14, 3, 11], [66, 27, 8], [31, 12, 21], [11, 16, 26]]

print("The list is :")
print(my_list)

check_list = [3, 10, 19, 29, 20, 15]
print("The check list is :")
print(check_list)

my_result = [row for row in my_list if not any(element in row for element in check_list)]

print("The result is :")
print(my_result)

輸出

The list is :
[[14, 3, 11], [66, 27, 8], [31, 12, 21], [11, 16, 26]]
The check list is :
[3, 10, 19, 29, 20, 15]
The result is :
[[66, 27, 8], [31, 12, 21], [11, 16, 26]]

說明

  • 定義了一個整數列表,並在控制檯上顯示。
  • 將一個整數列表定義為“check_list”,並在控制檯上顯示。
  • 使用列表解析遍歷元素,並使用“any”運算子。
  • 此處,檢查行中的元素是否與“check_list”中提供的元素匹配。
  • 如果匹配,該行就儲存在列表中。
  • 這被賦值給變數。
  • 它在控制檯上顯示為輸出。

更新於: 16-Sep-2021

105 次瀏覽

開啟 事業

完成課程認證

立即開始
廣告