從 Python 元組中移除巢狀記錄
當需要從元組中移除巢狀記錄/元組時,可以用一個簡單的迴圈、'isinstance' 方法以及 enumerate 方法。
enumerate 方法向給定的可迭代物件新增一個計數器,然後返回它。'isinstance' 方法檢查給定的引數是否屬於特定的資料型別。
下面是一個演示示例:
示例
tuple_1 = (11, 23, (41, 25, 22), 19) print("The tuple is : ") print(tuple_1) my_result = tuple() for count, elem in enumerate(tuple_1): if not isinstance(elem, tuple): my_result = my_result + (elem, ) print("Elements after removing the nested tuple is : ") print(my_result)
輸出
The tuple is : (11, 23, (41, 25, 22), 19) Elements after removing the nested tuple is : (11, 23, 19)
說明
- 定義了一個元組,並將其顯示在控制檯中。
- 定義另一個空元組。
- 對第一個元組進行列舉,並進行迭代處理。
- 如果元組中的元素不是特定型別的例項,則該元素將新增到空列表中。
- 此操作分配給一個變數。
- 它作為輸出顯示在控制檯中。
廣告