Python: assigning a tuple at the same time as a conversion type

I am reading a tab of 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')

      

This works well, but I want me to convert those x and y coordinates that are read from the string line

to a float. What's 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 doesn't work. Is there an elegant way to do this or do I need to manually convert afterwards, how self.x1 = float(self.x1)

?

+3


source to share


3 answers


You cannot do it 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 you need to do:

splitted = line.split('\t')
self.id = splitted.pop(0)
self.x1, self.y1, self.x2, self.y2 = map(float, splitted)

      

+6


source


I have asked this many times.

The best way I have come up with is to define a list of input conversion functions and then solidify them with arguments:



identity = lambda x: x
input_conversion = [identity, float, float, float, float]
self.id, self.x1, self.y1, self.x2, self.y2 = (
  f(x) for f, x in zip(input_conversion, line.split('\t')))

      

+3


source


You cannot do anything like what you are trying to do. But there are options.

In this case, you are trying to convert everything but the first value to float

. You can do it like this:

bits = line.split('\t')
self.id = bits.pop()
self.x1, self.y1, self.x2, self.y2 = map(float, bits)

      

+1


source







All Articles