I want to transform a string such as following:
' 1 , 2 , , , 3 '
into a list of non-empty elements:
['1', '2', '3']
My solution is this list comprehension:
print [el.strip() for el in mystring.split(",") if el.strip()]
Just wonder, is there a nice, pythonic way to write this comprehension without calling el.strip()
twice?
To remove duplicates from a list in Python, iterate through the elements of the list and store the first occurrence of an element in a temporary list while ignoring any other occurrences of that element. The basic approach is implemented in the naive method by: Using a For-loop to traverse the list.
What are duplicates in a list? If an integer or string or any items in a list are repeated more than one time, they are duplicates.
You can use a generator inside the list comprehension:
[x for x in (el.strip() for el in mylist.split(",")) if x]
# \__________________ ___________________/
# v
# internal generator
The generator thus will provide stripped elements, and we iterate over the generator, and only check the truthiness. We thus save on el.strip()
calls.
You can also use map(..)
for this (making it more functional):
[x for x in map(str.strip, mylist.split(",")) if x]
# \______________ ________________/
# v
# map
But this is basically the same (although the logic of the generator is - in my opinion - better encapsulated).
As a simple alternative to get a list of non-empty elements (in addition to previous good answers):
import re
s = ' 1 , 2 , , , 3 '
print(re.findall(r'[^\s,]+', s))
The output:
['1', '2', '3']
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