組合 Python 元組列表中的元組
對於資料分析,我們有時採用 Python 中可用的資料結構組合。列表可以包含元組作為其元素。在本文中,我們將瞭解如何將元組的每個元素與另一個給定的元素組合,並生成列表元組組合。
使用 for 迴圈
在下面的方法中,我們建立 for 迴圈,透過獲取元組的每個元素並在列表中的元素之間迴圈,來建立元素對。
示例
Alist = [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')] # Given list of tuple print("List of tuples : \n",Alist) # Combine tuples in list of tuples res = [(t1, t2) for i, t2 in Alist for t1 in i] # print result print("The list tuple combination : \n" ,res)
輸出
執行上述程式碼後,我們會得到以下結果 -
List of tuples : [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')] The list tuple combination : [(2, 'Mon'), (8, 'Mon'), (9, 'Mon'), (7, 'Wed'), (5, 'Wed'), (6, 'Wed')]
使用乘積
itertools 模組具有名為 product 的迭代器,它建立傳遞給它的引數的笛卡爾積。在這個示例中,我們設計 for 迴圈來遍歷元組的每個元素,並與元組中的非列表元素形成一對。
示例
from itertools import product Alist = [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')] # Given list of tuple print("List of tuples : \n",Alist) # Combine tuples in list of tuples res = [x for i, j in Alist for x in product(i, [j])] # print result print("The list tuple combination : \n" ,res)
輸出
執行上述程式碼後,我們會得到以下結果 -
List of tuples : [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')] The list tuple combination : [(2, 'Mon'), (8, 'Mon'), (9, 'Mon'), (7, 'Wed'), (5, 'Wed'), (6, 'Wed')]
廣告