如何在 Python 中獲取巢狀元組中的唯一元素
當需要獲取巢狀元組中的唯一元素時,可以使用巢狀迴圈和“set”運算子。
Python 帶有一種稱為“set”的資料型別。此“set”僅包含唯一元素。
set 用於執行交集、差集、並集和對稱差等運算。
下面是同樣的演示 -
示例
my_list_1 = [(7, 8, 0), (0 ,3, 45), (3, 2, 22), (45, 12, 9)]
print ("The list of tuple is : " )
print(my_list_1)
my_result = []
temp = set()
for inner in my_list_1:
for elem in inner:
if not elem in temp:
temp.add(elem)
my_result.append(elem)
print("The unique elements in the list of tuples are : ")
print(my_result)輸出
The list of tuple is : [(7, 8, 0), (0, 3, 45), (3, 2, 22), (45, 12, 9)] The unique elements in the list of tuples are : [7, 8, 0, 3, 45, 2, 22, 12, 9]
說明
- 定義一個元組列表,並顯示在控制檯上。
- 建立一個空列表,並建立一個空 set。
- 列表進行迭代,並檢查列表中是否存在它。
- 如果沒有,則將其新增到列表和空 set 中。
- 此結果被分配給一個值。
- 它在控制檯上作為輸出顯示。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP