gpt4 book ai didi

python - 如何将列表的值插入嵌套列表?

转载 作者:行者123 更新时间:2023-12-04 10:30:42 27 4
gpt4 key购买 nike

我有这样的嵌套列表:

ll =
[[[0, 0.01655718859584843],
[1, 0.03777621092166489],
[2, 0.02162311536578436],
[3, 0.02907007584458954]],
[[0, 0.011912058415296719],
[1, 0.07967490411502279],
[2, 0.04067120278932331],
[3, 0.05439173103552319]]]

我想在第二个列表中插入条目:
uu =
[4577911, 4577821]

到相应子列表的索引 0 中。

所以进入 ll的第一个子列表我想插入 uu 的第一个条目像这样:
[[[4577911, 0, 0.01655718859584843],
[4577911, 1, 0.03777621092166489],
[4577911, 2, 0.02162311536578436],
[4577911, 3, 0.02907007584458954]],
[[4577821, 0, 0.011912058415296719],
[4577821, 1, 0.07967490411502279],
[4577821, 2, 0.04067120278932331],
[4577821, 3, 0.05439173103552319]]]

但是我的代码提供了奇怪的结果
tu = ([[[u + x] for x in t] for t in ll for u in uu])

我怎样才能正确地做到这一点?

最佳答案

zip 中使用嵌套列表理解

例如:

ll = [[[0, 0.01655718859584843],
[1, 0.03777621092166489],
[2, 0.02162311536578436],
[3, 0.02907007584458954]],
[[0, 0.011912058415296719],
[1, 0.07967490411502279],
[2, 0.04067120278932331],
[3, 0.05439173103552319]]]

uu = [4577911, 4577821]

print([[[i] + k for k in j] for i, j in zip(uu, ll)])

输出:
[[[4577911, 0, 0.01655718859584843],
[4577911, 1, 0.03777621092166489],
[4577911, 2, 0.02162311536578436],
[4577911, 3, 0.02907007584458954]],
[[4577821, 0, 0.011912058415296719],
[4577821, 1, 0.07967490411502279],
[4577821, 2, 0.04067120278932331],
[4577821, 3, 0.05439173103552319]]]

关于python - 如何将列表的值插入嵌套列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60434116/

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