[英]How to replace a nested list in multi-dimensional array python with another list based on a certain condition
I am trying to replace a nested list in my_list on a certain condition.我试图在特定条件下替换 my_list 中的嵌套列表。 In this case, I want to replace the 'HB2_DF_en1a'
with the element of 2nd list and so on for the rest, if it finds ''
in the previous list.在这种情况下,我想用第二个列表的元素替换'HB2_DF_en1a'
,如果在前一个列表中找到''
,则以此类推。 The number of ''
and elements in the 2nd list are the same. ''
和第二个列表中的元素数量相同。
my_list = [[[['', ''], ['HB2_DF_en1a', 'HB2_DF_en2a']]],
[[[''], ['XY1_DF_en1a']],
[['Io01[4:2]'], ['XY_DF1']]],
[[['', ''], ['XY2_DF_en1a', 'XY2_DF_en2a']]]]
2nd_list = [['XY1_IPC'],
['cat_lpm'],
['XY_ABC1'],
['XY2_IPC'],
['XY_ABC2', 'XY2_IPC']]
I am trying -我在尝试 -
b = 0
for i in my_list:
for j in i:
for k in j:
if a == '':
k+1.append(2nd_list[b])
b = b+1
The output I am looking for -我正在寻找的输出 -
my_list = [[[['', ''], [['XY1_IPC'], ['cat_lpm']]]],
[[[''], ['XY_ABC1']]],
[['Io01[4:2]'], ['XY_DF1']],
[[['', ''],
[['XY2_IPC'], ['XY_ABC2', 'XY2_IPC']]]]]
Try like this:像这样尝试:
my_list = [
[[["", ""], ["HB2_DF_en1a", "HB2_DF_en2a"]]],
[[[""], ["XY1_DF_en1a"]], [["Io01[4:2]"], ["XY_DF1"]]],
[[["", ""], ["XY2_DF_en1a", "XY2_DF_en2a"]]],
]
reference_list = [
["XY1_IPC"],
["cat_lpm"],
["XY_ABC1"],
["XY2_IPC"],
["XY_ABC2", "XY2_IPC"],
]
ref_index = 0
for level1 in my_list:
for level2 in level1:
for index, value in enumerate(level2):
if value[0] == "":
for change_index, times in enumerate(value):
level2[1][change_index] = reference_list[ref_index]
ref_index = ref_index + 1
# Print result:
print(my_list)
Result:结果:
[
[
[
['', ''],
[
['XY1_IPC'],
['cat_lpm']
]
]
],
[
[
[''],
[
['XY_ABC1']
]
],
[
['Io01[4:2]'],
['XY_DF1']
]
],
[
[
['', ''],
[
['XY2_IPC'],
['XY_ABC2', 'XY2_IPC']
]
]
]
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.