在 Python 中提取具有 K 位元素的元組
當需要提取具有特定數量元素的元組時,可以使用列表解析。它會遍歷元組列表中的元素,並提出需要滿足的條件。這將過濾掉特定元素,並將它們儲存在另一個變數中。
以下是同樣的演示 −
示例
my_list = [(34, 56), (45, 6), (111, 90), (11, 35), (78, )] print("The list is : ") print(my_list) K = 2 print("The value of K has been initialized to" + "str(K)") my_result = [sub for sub in my_list if all(len(str(elem)) == K for elem in sub)] print("The tuples extracted are : ") print(my_result)
輸出
The list is : [(34, 56), (45, 6), (111, 90), (11, 35), (78,)] The value of K has been initialized tostr(K) The tuples extracted are : [(34, 56), (11, 35), (78,)]
說明
定義了一個元組列表,並在控制檯中顯示。
為“K”初始化一個值。
使用列表解析遍歷元組列表。
它檢查列表中所有元組的大小是否相同。
將它轉換為列表,並將其分配給一個變數。
在控制檯上顯示為輸出。
廣告