Issue
I'm looking for a way to completely delete an element from a tuple based on a condition in Python. The following is a subsection of my code. If it's possible I would like the solution to do its thing in the third if-clause to keep the structure of my main code.
Here is my code:
import ast
data = []
myList=[0,"[('AA', 'BB'), ('CC', 'DD'), ('EE', 'FF'), ('GG', 'HH')]"]
for a in ast.literal_eval(myList[1]):
Value = a[0]
Type = a[1]
if(Type == "BB"):
Value="XX"
if(Type == "DD"):
Value="YY"
if(Type == "FF"):
Value=""
data.append([myList[0], Value])
print(data)
Current Output:
[[0, 'XX'], [0, 'YY'], [0, ''], [0, 'GG']]
What I need:
[[0, 'XX'], [0, 'YY'], [0, 'GG']]
Solution
An easy way to achieve this would be to use the continue
statement in your third conditional. Continue statements can be used in loops to skip the execution of the remaining code in the loop and return control to the beginning of the loop at the next iteration.
In your case:
if(Type == "FF"):
continue
data.append([myList[0], Value])
would mean that if type is 'FF' then the data.append statement is skipped and the entry is not added to your list.
Answered By - rymo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.