简体   繁体   中英

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

I'm new to Python and I have a question on involving data structures and algorithms(which are essential skills that a programmer should have)

There are two lists L1 AND 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]]]

Looks like you need this:

L1_it = iter(L1)

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

This can be expanded as follows:

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)

Both methods give the same result:

[[['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]]]

To get to this piece of code, we observe that the expected result is of the same structure as L2 , except that the elements in running order from L1 are appended to each sublist in L2 as if it were flattened.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM