I am iterating over nested lists with a for-loop and would like to insert a new nested lists at the next index if a condition is met. During the next iterations these newly added lists should be skipped. Example:
input_lst = [["a", "b"], ["a", "d"], ["e", "f"]]
for sublst in input_lst:
if sublst[0] == "a":
new_sublst = []
input_lst.insert((input_lst.index(sublst) 1), new_sublst)
new_sublst.insert(0, "a")
new_sublst.insert(1, "z")
print(input_lst)
Intended outcome:
[["a", "b"], ["a", "z"], ["a", "d"], ["a", "z"], ["e", "f"]]
Actual outcome - endless loop with:
[["a", "b"], ["a", "z"], ["a", "z"], ["a", "z"], ["a", "z"] ...
CodePudding user response:
Try this :
input_lst = [["a", "b"], ["a", "d"], ["e", "f"]]
result = []
for sublst in input_lst:
result.append(sublst)
if sublst[0] == "a":
result.append(["a", "z"])
print(result)
Alternatively:
input_lst = [["a", "b"], ["a", "d"], ["e", "f"]]
for sublst in input_lst:
if sublst == ["a","z"]:
continue
if sublst[0] == "a":
new_sublst = []
input_lst.insert((input_lst.index(sublst) 1), new_sublst)
new_sublst.insert(0, "a")
new_sublst.insert(1, "z")
print(input_lst)
Result:
[['a', 'b'], ['a', 'z'], ['a', 'd'], ['a', 'z'], ['e', 'f']]
Point to note:
If you add ["a","z"] as the next element in the list when current sublst start with "a", you created a endless-loop because next iteration is definitely starting with an "a" as in ["a", "z"].
Using a new list to store result of each iteration can solve the problem. Or you can skip adding another ["a","z"] when the current sublst is ["a","z"].
CodePudding user response:
You could use a second list:
input_lst = [["a", "b"], ["a", "d"], ["e", "f"]]
new_sublst = ["a", "z"]
output_lst = []
for sublst in input_lst:
output_lst.append(sublst)
if sublst[0] == "a":
output_lst.append(new_sublst)
Output:
[['a', 'b'], ['a', 'z'], ['a', 'd'], ['a', 'z'], ['e', 'f']]
CodePudding user response:
Adding to the answer of @ytung-dev, which tests against a specific condition, I came up with a solution that uses a second list as a negative to compare against. Maybe someone else will find this useful:
input_lst = [["a", "b"], ["a", "d"], ["e", "f"]]
input_lst_negative = []
for sublst in input_lst:
if (sublst[0] == "a") and (sublst not in input_lst_negative):
new_sublst = []
input_lst.insert((input_lst.index(sublst) 1), new_sublst)
new_sublst.insert(0, "a")
new_sublst.insert(1, "z")
input_lst_negative.append(new_sublst)
print(input_lst)
Output:
[['a', 'b'], ['a', 'z'], ['a', 'd'], ['a', 'z'], ['e', 'f']]