Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: tuple assignment while at same time converting type

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)?

like image 652
Joe Zocker Avatar asked Sep 06 '26 14:09

Joe Zocker


1 Answers

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)
like image 184
Bakuriu Avatar answered Sep 08 '26 03:09

Bakuriu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!