Python: 元组赋值同时转换类型
Python: tuple assignment while at same time converting type
我正在将字符串中的制表符分隔值读取到这样的对象中:
class Node(rect):
def __init__(self, line):
(self.id, self.x1, self.y1, self.x2, self.y2) = line.split('\t')
这很好用,但是假设我想将从字符串 line
中读取的那些 x 和 y 坐标转换为浮点数。最pythonic的方法是什么?我想像
(self.id, float(self.x1), float(self.y1), float(self.x2), float(self.y2)) = line.split('\t')
这当然行不通。有没有一种优雅的方法可以做到这一点,或者我必须像 self.x1 = float(self.x1)
?
那样手动转换
你不能做任何你想做的事情。但也有选择。
在这种情况下,您尝试将除第一个值以外的所有值都转换为 float
。你可以这样做:
bits = line.split('\t')
self.id = bits.pop()
self.x1, self.y1, self.x2, self.y2 = map(float, bits)
你不能在一行中做到这一点,但你可以这样做:
self.id, *rest = line.split('\t')
self.x1, self.y1, self.x2, self.y2 = map(float, rest)
如果你在python2,那么你必须做:
splitted = line.split('\t')
self.id = splitted.pop(0)
self.x1, self.y1, self.x2, self.y2 = map(float, splitted)
这个问题我自己问过很多次了。
我想出的最好方法是定义一个输入转换函数列表,然后用参数压缩它们:
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')))
我正在将字符串中的制表符分隔值读取到这样的对象中:
class Node(rect):
def __init__(self, line):
(self.id, self.x1, self.y1, self.x2, self.y2) = line.split('\t')
这很好用,但是假设我想将从字符串 line
中读取的那些 x 和 y 坐标转换为浮点数。最pythonic的方法是什么?我想像
(self.id, float(self.x1), float(self.y1), float(self.x2), float(self.y2)) = line.split('\t')
这当然行不通。有没有一种优雅的方法可以做到这一点,或者我必须像 self.x1 = float(self.x1)
?
你不能做任何你想做的事情。但也有选择。
在这种情况下,您尝试将除第一个值以外的所有值都转换为 float
。你可以这样做:
bits = line.split('\t')
self.id = bits.pop()
self.x1, self.y1, self.x2, self.y2 = map(float, bits)
你不能在一行中做到这一点,但你可以这样做:
self.id, *rest = line.split('\t')
self.x1, self.y1, self.x2, self.y2 = map(float, rest)
如果你在python2,那么你必须做:
splitted = line.split('\t')
self.id = splitted.pop(0)
self.x1, self.y1, self.x2, self.y2 = map(float, splitted)
这个问题我自己问过很多次了。
我想出的最好方法是定义一个输入转换函数列表,然后用参数压缩它们:
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')))