繁体   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