使用 Python 输入模块指定序列或列表的长度 [英] Specify length of Sequence or List with Python typing module
问题描述
我正在尝试 Python typing
模块.
I'm giving the Python typing
module a shot.
我知道像下面这样指定 List
的长度是有效的*:
I know that it's valid to specify the length of a List
like the following*:
List[float, float, float] # List of 3 floats <-- NOTE: this is not valid Python
是否有更长列表的简写?如果我想将它设置为 10 个浮点数怎么办?
Is there any shorthand for longer lists? What if I want to set it to 10 floats?
List[float * 10] # This doesn't work.
如果这是可能的任何想法,这会很方便.
Any idea if this is possible, this would be handy.
*注意:事实证明,以这种方式向 Sequence[]
(及其子类)提供多个参数目前不是有效的 Python.此外,目前无法以这种方式使用 typing
模块指定 Sequence
长度.
*NOTE: It turns out that supplying multiple arguments to Sequence[]
(and its subclasses) in this manner is currently NOT valid Python. Furthermore, it is currently not possible to specify a Sequence
length using the typing
module in this way.
推荐答案
你不能.列表是可变的、可变长度结构.如果您需要固定长度的结构,请改用元组:
You can't. A list is a mutable, variable length structure. If you need a fixed-length structure, use a tuple instead:
Tuple[float, float, float, float, float, float, float, float, float, float]
或者更好的是,使用一个命名元组,它具有索引和命名属性:
Or better still, use a named tuple, which has both indices and named attributes:
class BunchOfFloats(NamedTuple):
foo: float
bar: float
baz: float
spam: float
ham: float
eggs: float
monty: float
python: float
idle: float
cleese: float
列表只是固定长度数据结构的错误数据类型.
A list is simply the wrong data type for a fixed-length data structure.
这篇关于使用 Python 输入模块指定序列或列表的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!