I have a list that is the result of a string .split.
E.g. for the string numbers = "1/2//4//6":
>>> numbers = numbers.split("/")
['1', '2', '', '4', '', '5']
I'd like to create a list based on that where any empty values (i.e '') are replaced with a number that increments only with empty values. So the end result should be:
[1, 2, 1, 4, 2, 6]
The first empty value has been replaced with 1 and the second with 2.
I've created a loop that can do this, but frankly, it's an eyesore and takes me back to Java:
auto = 1
for i,number in enumerate(numbers):
if number == "":
numbers[i] = auto
auto += 1
else:
numbers[i] = int(number)
I'd love to be able to do this without using an external variable and, ideally, via a list comprehension instead.
Is this possible in Python?
You can use itertools.count:
import itertools
c = itertools.count(1)
numbers = "1/2//4//6"
result = [int(i) if i else next(c) for i in numbers.split('/')]
Output:
[1, 2, 1, 4, 2, 6]
Edit: if you wish to avoid "external" variables related to the incrementation process, and if you are willing to store the split results of numbers, you can use enumerate. However, it is not as efficient nor as clean as using itertools.count:
numbers = "1/2//4//6".split('/')
result = [int(a) if a else sum(not c for c in numbers[:i])+1 for i, a in enumerate(numbers)]
Output:
[1, 2, 1, 4, 2, 6]
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