如何基于属于另一个2D列表的1D元素对2D列表中的元素进行分组/合并?

时间:2019-03-23 07:29:36

标签: python python-3.x algorithm multidimensional-array data-structures

我是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]]]

1 个答案:

答案 0 :(得分:0)

看起来您需要这个:

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开始运行的元素被附加到{{ 1}},就好像被压扁了。