在 Python 中移除長度為 K 的元組
當需要移除特定長度為“K”的元組時,可以使用列表解析。
以下是對此內容的演示 −
示例
my_list = [(32, 51), (22,13 ), (94, 65, 77), (70, ), (80, 61, 13, 17)]
print("The list is : " )
print(my_list)
K = 1
print("The value of K is ")
print(K)
my_result = [ele for ele in my_list if len(ele) != K]
print("The filtered list is : ")
print(my_result)輸出
The list is : [(32, 51), (22, 13), (94, 65, 77), (70,), (80, 61, 13, 17)] The value of K is 1 The filtered list is : [(32, 51), (22, 13), (94, 65, 77), (80, 61, 13, 17)]
解釋
將定義一個元組列表,並將其顯示在控制檯上。
將分配 K 的值並在控制檯上顯示該值。
列表解析用於檢查元組列表中每個元素的長度。
將其分配給一個變數
將其作為輸出顯示在控制檯上。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP