從 Python 列表中移除每個元素均為 None 的元組
當需要從元組列表中移除包含“None”元素的元組時,可以使用列表解析。
以下是實現這部分內容的演示:
示例
my_list = [(2, None, 12), (None, None, None), (23, 64), (121, 13), (None, ), (None, 45, 6)]
print("The list is : ")
print(my_list)
my_result = [sub for sub in my_list if not all(elem == None for elem in sub)]
print("The None tuples have been removed, the result is : " )
print(my_result)輸出
The list is : [(2, None, 12), (None, None, None), (23, 64), (121, 13), (None,), (None, 45, 6)] The None tuples have been removed, the result is : [(2, None, 12), (23, 64), (121, 13), (None, 45, 6)]
解釋
元組列表定義之後,會在控制檯上顯示該列表。
列表解析用於遍歷該列表。
“all”條件用於檢視是否存在“None”元素。
當存在“None”元素時,將對其進行篩選。
剩下的資料將分配給一個變數。
該變數將作為輸出顯示。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP