How can I do something like the following in Python?
row = [unicode(x.strip()) if x for x in row]
Basically, a list comprehension where you carry out a function if the variable exists.
Thanks!
Conditional Logic You can add an if statement at the end of a list comprehension to return only items which satisfy a certain condition. For example, the code below returns only the numbers in the list that are greater than two. This code returns a list of heights greater than 160 cm.
List comprehensions are a syntactic form in Python allowing the programmer to loop over and transform an iterable in one line.
Answer: You can use any expression inside the list comprehension, including functions and methods.
The "if" goes at the end"
row = [unicode(x.strip()) for x in row if x]
So close.
row = [unicode(x.strip()) for x in row if x]
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