gpt4 book ai didi

python - 如何将多维列表中的元素附加到第二个多维列表中

转载 作者:行者123 更新时间:2023-12-04 17:16:49 25 4
gpt4 key购买 nike

我正在尝试将多维列表中的元素附加到第二个多维列表中。这是我写的代码-

my_list = [[['b', ['a'], 'c'], ['d', ['a', 'b'], 'e']], 
[['j', ['a', 'f']], ['q', 't']]]
ref_list = [[['q', 'w', 't'], ['y', 'u']],
[['s', 'o'], ['p', 'k', 'l']]]

newlist = []
for num, i in enumerate(my_list):
small_list = []
for num_1, j in enumerate(i):
semilist = []
for k in j:
if isinstance(k, list):
onelist = []
for a in k:
for ii in ref_list[num][num_1]:
onelist.append(ii)
semilist.append(onelist)
else:
semilist.append(k)
small_list.append(semilist)
newlist.append(small_list)

print(newlist)

我得到的输出是 -

[[['b', ['q', 'w', 't'], 'c'], ['d', ['y', 'u', 'y', 'u'], 'e']], [['j', ['s', 'o', 's', 'o']], ['q', 't']]]

我正在寻找的输出是这样的 -

[[['b', ['q', 'w', 't'], 'c'], ['d', ['y', 'u'], 'e']], [['j', ['s', 'o']], ['p', 'k', 'l']]]

我想用“ref_list”的元素替换“my_list”最内层列表的元素。

最佳答案

尝试:

ref_list_flat = [l for sublist in ref_list for l in sublist]

for i, l1 in enumerate(my_list):
for j, l2 in enumerate(l1):
#check if this is the innermost list
if not any(isinstance(l3, list) for l3 in l2):
my_list[i][j] = ref_list_flat.pop(0)
else:
for k, l3 in enumerate(l2):
if isinstance(l3, list):
my_list[i][j][k] = ref_list_flat.pop(0)

>>> my_list
[[['b', ['q', 'w', 't'], 'c'], ['d', ['y', 'u'], 'e']],
[['j', ['s', 'o']], ['p', 'k', 'l']]]

关于python - 如何将多维列表中的元素附加到第二个多维列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68535054/

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