gpt4 book ai didi

python - 如何根据属于另一个二维列表的一维元素对二维列表中的元素进行分组/俱乐部?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:37:38 25 4
gpt4 key购买 nike

我刚接触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 中的每个子列表,就好像它被展平了一样。

关于python - 如何根据属于另一个二维列表的一维元素对二维列表中的元素进行分组/俱乐部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55311621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com