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)
?
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)
I've asked this myself many times.
The best way I came up with was to define a list of input conversion functions and then zipping them with the 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')))
You can't do anything like what you're trying to do. But there are options.
In this case, you're trying to convert everything but the first value to a float
. You could do that like this:
bits = line.split('t')
self.id = bits.pop()
self.x1, self.y1, self.x2, self.y2 = map(float, bits)
链接地址: http://www.djcxy.com/p/53560.html
上一篇: 确定Python函数中返回值的数量
下一篇: Python:元组赋值,同时转换类型