为什么 List 不能包含多种类型? [英] Why can't List contain multiple types?
问题描述
您可以在元组或列表中混合类型.为什么不能在输入提示中指定?
<预><代码>>>>从输入导入元组,列表>>>t = ('a', 1)>>>l = ['a', 1]>>>t2: 元组[str, int] = ('a', 1)>>>l2:列表[str, int] = ['a', 1]类型错误:用于输入的参数太多.列表;实际 2,预期 1在类型理论中,列表是包含一种类型值的同构结构.因此,List
只接受一种类型,并且该列表的每个元素都必须具有该类型.
然而,类型理论还提供和类型,您可以将其视为从一组固定类型中选择的一个值的包装器.typing.Union
支持和类型.要指定列表是 int
和 str
值的混合,请使用
List[Union[str, int]]
作为类型提示.
相比之下,元组是产品类型的一个例子,一种由一组固定类型组成的类型,其值是一组值,来自产品类型中的每个类型.Tuple[int,int,int]
、Tuple[str,int]
和 Tuple[int,str]
都是不同的类型,区分两者由产品中的类型的数量和它们出现的顺序决定.
You can mix types inside tuples or lists. Why can't you specify that in typing hints?
>>> from typing import Tuple, List
>>> t = ('a', 1)
>>> l = ['a', 1]
>>> t2: Tuple[str, int] = ('a', 1)
>>> l2: List[str, int] = ['a', 1]
TypeError: Too many parameters for typing.List; actual 2, expected 1
In type theory, a list is a homogenous structure containing values of one type. As such, List
only takes a single type, and every element of that list has to have that type.
However, type theory also provides sum types, which you can think of as a wrapper around exactly one value selected from some fixed set of types. A sum type is supported by typing.Union
. To specify that a list is a mix of int
and str
values, use
List[Union[str, int]]
as the type hint.
By contrast, a tuple is an example of a product type, a type consisting of a fixed set of types, and whose values are a collection of values, one from each type in the product type. Tuple[int,int,int]
, Tuple[str,int]
and Tuple[int,str]
are all distinct types, distinguished both by the number of types in the product and the order in which they appear.
这篇关于为什么 List 不能包含多种类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!