Reputation: 231
I am trying to replace a nested list in my_list on a certain condition. 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. 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']]]]]
Upvotes: 0
Views: 147
Reputation: 1005
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']
]
]
]
]
Upvotes: 1