I'm reading tab separated values from strings into an object like this:
class Node(rect):
def __init__(self, line):
(self.id, self.x1, self.y1, self.x2, self.y2) = line.split('\t')
That works fine, but say I want to convert those x and y coordinates, which are read from the string line, to floats. What is the most pythonic way to do this? I imagine something like
(self.id, float(self.x1), float(self.y1), float(self.x2), float(self.y2)) = line.split('\t')
which of course does not work. Is there an elegant way to do this or do I have to manually convert afterwards like self.x1 = float(self.x1)?
You can't do that on one line but you can do something like:
self.id, *rest = line.split('\t')
self.x1, self.y1, self.x2, self.y2 = map(float, rest)
If you are on python2 then you have to do:
splitted = line.split('\t')
self.id = splitted.pop(0)
self.x1, self.y1, self.x2, self.y2 = map(float, splitted)
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