I have list that looks like,
tmp_text = ['col1','','col2','col3','','']
I am trying to replace the empty elements in the list with an iterative value, this is the output I am trying to get
tmp_text = ['col1','Nan1','col2','col3','Nan2','Nan3']
Basically I need to replace the empty elements with the string 'NaN' but the with an iterative number attached to it. I need some help on how to do this.
CodePudding user response:
You can use itertools.count()
, which returns an iterator over numbers:
>>> import itertools
>>> tmp_text = ['col1','','col2','col3','','']
>>> counter = itertools.count(1)
>>> new_text = [x or f'Nan{next(counter)}' for x in tmp_text]
['col1', 'Nan1', 'col2', 'col3', 'Nan2', 'Nan3']
CodePudding user response:
Using the assignment/walrus operator in python 3.8 you can do this pretty easily
tmp_text = ['col1','','col2','col3','','']
i = 0
result = [x or f'Nan{(i:=i 1)}' for x in tmp_text]
['col1', 'Nan1', 'col2', 'col3', 'Nan2', 'Nan3']
CodePudding user response:
Here's one way you could do it
from itertools import counter
nan_counter = counter(1)
tmp_txt = [s if s else f'NaN{next(nan_counter)}' for s in tmp_txt]
CodePudding user response:
Why do you need to do this over list comprehension however? Each iteration you need to depend on a variable that will be conditionally updated.
However, there is still a way if you are doing python 3.8 like so
[x or f"Nan{(y := y 1)}" for index, x in enumerate(tmp_text) if not index and (y := 0) or True]
Will give you
['col1', 'Nan1', 'col2', 'col3', 'Nan2', 'Nan3']
I strongly advise against this as it is not really readable and has a questionable logic checking just to initialize a variable via walrus