Python - 提取包含任意布林真值的列


當需要提取包含任意布林真值的列時,可以使用列表推導和“any”運算子。

以下是對此內容的說明——

示例

 現場演示

my_tuple = [[False, True], [False, False], [True, False, True], [False]]

print("The tuple is :")
print(my_tuple)

my_result = [row for row in my_tuple if any(element for element in row)]

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

輸出

The tuple is :
[[False, True], [False, False], [True, False, True], [False]]
The result is
[[False, True], [True, False, True]]

說明

  • 定義了一個列表的列表,並顯示在控制檯中。

  • 使用列表推導來檢查列表中是否存在任何元素。

  • “any”運算子給出真或假的結果。

  • 將其轉換為列表並賦值給變數。

  • 這是顯示在控制檯上的輸出內容。

更新時間:06-9 月 -2021

161 次瀏覽

職業生涯 衝刺開始

完成課程獲得認證

開始
廣告
© . All rights reserved.