簡體   English   中英

如何根據屬於另一個2D列表的1D元素對2D列表中的元素進行分組/分類?

[英]How to group/club elements in a 2D list based on the 1D elements belonging to another 2D list?

我是Python的新手,我有一個涉及數據結構和算法的問題(這是程序員應該具備的基本技能)

L1和L2有兩個列表。

L1= [[0.0, 0.22],[0.0, 0.13],[0.03, 0.19],[0.14, 0.49],[0.2, 0.55], 
     [0.5,0.61],[0.56, 0.72],[0.62, 0.82],[0.0, 0.11], [0.03, 0.31],
     [0.12, 0.47], [0.32, 0.55], [0.48, 0.72], [0.56, 0.75],[0.0, 0.09], 
     [0.03, 0.16]]
L2= [['eɪ'], ['æ', 'f', 'ɹ', 'i', 'k', 'ʌ', 'n'],['eɪ', 'ʤ', 'ʌ', 'n', 
     't', 's'], ['ɔ', 'l']]
  #I want the final output like this as a 3D array
   [[['eɪ',0.0, 0.22]],[['æ',0.0, 0.13],['f',0.03, 0.19],['ɹ',0.14, 0.49],['i', 0.2, 0.55], 
     ['k',0.5,0.61],['ʌ',0.56, 0.72],['n',0.62, 0.82]],[['eɪ',0.0, 0.11], ['ʤ',0.03, 0.31],
     ['ʌ',0.12, 0.47], ['n',0.32, 0.55], ['t',0.48, 0.72], ['s',0.56, 0.75]],[['ɔ',0.0, 0.09], 
     ['l',0.03, 0.16]]]

看起來你需要這個:

L1_it = iter(L1)

result = [[[L2_element, *next(L1_it)] for L2_element in sublist] for sublist in L2]  

這可以擴展如下:

L1_it = iter(L1)

result = []

for L2_sublist in L2:
    result_sublist = []
    for L2_element in L2_sublist:
        result_sublist.append([L2_element, *next(L1_it)])

    result.append(result_sublist)

兩種方法都給出了相同的結果:

[[['eɪ', 0.0, 0.22]], [['æ', 0.0, 0.13], ['f', 0.03, 0.19], ['ɹ', 0.14, 0.49], ['i', 0.2, 0.55], ['k', 0.5, 0.61], ['ʌ', 0.56, 0.72], ['n', 0.62, 0.82]], [['eɪ', 0.0, 0.11], ['ʤ', 0.03, 0.31], ['ʌ', 0.12, 0.47], ['n', 0.32, 0.55], ['t', 0.48, 0.72], ['s', 0.56, 0.75]], [['ɔ', 0.0, 0.09], ['l', 0.03, 0.16]]]

為了得到這段代碼,我們觀察到預期結果與L2具有相同的結構,除了從L1運行順序的元素被附加到L2每個子列表,就像它被展平一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM