I am trying to put items from two lists together, based on a condition, to create a third list as output. Even though I am a novice, this is relatively straightforward. However, I am trying to make one part of the loop run only once and this where I struggle. Is there a way to do this?
The data comes from a large DataFrame of text data. But I created a simplified version of the problem, to try and solve it more easily (without luck):
a = [1, 2, 3, 4, 5]
A = [4, 5]
b = []
for i in a:
if i in A:
b.append(3.5) # My aim is to make this line run only once
b.append(i)
else:
b.append(i)
print(b)
This gives:
[1, 2, 3, 3.5, 4, 3.5, 5]
How can I get the following result?
[1, 2, 3, 3.5, 4, 5]
You can add a Boolean value that is initialised to false and is then set to true directly after b.append(3.5) is run. If you check this value in the if statement it will only run once.
a = [1, 2, 3, 4, 5]
A = [4, 5]
b = []
ran = False
for i in a:
if i in A and not ran:
b.append(3.5) # My aim is to make this line run only once
ran = True
b.append(i)
else:
b.append(i)
print(b)
You could add a boolean flag for this:
a = [1, 2, 3, 4, 5]
A = [4, 5]
b = []
extend = True
for i in a:
if i in A:
if extend:
b.append(3.5) # My aim is to make this line run only once
extend = False
b.append(i)
else:
b.append(i)
print(b)
Edit: Actually, if your loop is really that simple, the other answers are more elegant, since except for the first execution, the if
and else
clauses are equal. If they are not, however, my code is the way to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With