Python 3 名元组位置
Python 3 name tuple position
如果我有坐标元组 (10.1, 15.2)
,我该怎么做才能将 10.1
简单地称为 x
而不是 coordinates[0]
,并且 y
而不是 coordinates[1]
?
我想这样做是为了在函数之间传递元组,同时仍然能够轻松调用 x
和 y
。我可以:
x = coordinates[0]
y = coordinated[1]
但这似乎是个坏主意——冗长而且我必须为每个函数重复它。
使用namedtuple:
> from collections import namedtuple
> c = namedtuple('Coords',['x','y'])
> xy = c(5,6)
> xy
=> Coords(x=5, y=6)
> xy.x
=> 5
> xy.y
=> 6
如果我有坐标元组 (10.1, 15.2)
,我该怎么做才能将 10.1
简单地称为 x
而不是 coordinates[0]
,并且 y
而不是 coordinates[1]
?
我想这样做是为了在函数之间传递元组,同时仍然能够轻松调用 x
和 y
。我可以:
x = coordinates[0]
y = coordinated[1]
但这似乎是个坏主意——冗长而且我必须为每个函数重复它。
使用namedtuple:
> from collections import namedtuple
> c = namedtuple('Coords',['x','y'])
> xy = c(5,6)
> xy
=> Coords(x=5, y=6)
> xy.x
=> 5
> xy.y
=> 6