用 Python 將元組列表轉換成數字
Python 具有廣泛的資料操作功能。我們有一個場景,其中提供了一個列表,其中元素是作為元組的對號。在本文中,我們將看到如何從列表元素(即元組)中提取唯一數字。
透過 re 和 set
我們可以使用正則表示式模組及其稱為 sub 的函式。它用於替換與正則表示式匹配的字串,而不是完全匹配。因此,我們設計一個正則表示式來將元組轉換為普通字串,然後應用 set 函式以獲得唯一數字。
示例
import re listA = [(21, 3), (13, 4), (15, 7),(8,11)] # Given list print("Given list : \n", listA) temp = re.sub(r'[\[\]\(\), ]', '', str(listA)) # Using set res = [int(i) for i in set(temp)] # Result print("List of digits: \n",res)
輸出
執行上面的程式碼,可得到以下結果 −
Given list : [(21, 3), (13, 4), (15, 7), (8, 11)] List of digits: [1, 3, 2, 5, 4, 7, 8])
透過 chain 和 set
itertools 模組提供了 chain 方法,我們可以使用該方法來獲取列表中的元素。然後建立一個空集,並將元素逐個新增到該集中。
示例
from itertools import chain listA = [(21, 3), (13, 4), (15, 7),(8,11)] # Given list print("Given list : \n", listA) temp = map(lambda x: str(x), chain.from_iterable(listA)) # Using set and add res = set() for i in temp: for elem in i: res.add(elem) # Result print("set of digits: \n",res)
輸出
執行上面的程式碼,可得到以下結果 −
Given list : [(21, 3), (13, 4), (15, 7), (8, 11)] set of digits: ['1', '3', '2', '5', '4', '7', '8'])
廣告