什么类型提示同时包含列表和元组?
What type-hint contains both list and tuple?
我有一个函数可以接受任何可以索引的变量作为输入,例如列表或元组。我如何在函数的类型提示中指出这一点?
您的方法正在接受 sequence, so use typing.Sequence
。这是一个泛型,因此您可以指定序列必须包含的对象类型:
from typing import Sequence
def foo(bar: Sequence[int]):
# bar is a sequence of integers
An iterable which supports efficient element access using integer indices via the __getitem__()
special method and defines a __len__()
method that returns the length of the sequence. Some built-in sequence types are list
, str
, tuple
, and bytes
.
我有一个函数可以接受任何可以索引的变量作为输入,例如列表或元组。我如何在函数的类型提示中指出这一点?
您的方法正在接受 sequence, so use typing.Sequence
。这是一个泛型,因此您可以指定序列必须包含的对象类型:
from typing import Sequence
def foo(bar: Sequence[int]):
# bar is a sequence of integers
An iterable which supports efficient element access using integer indices via the
__getitem__()
special method and defines a__len__()
method that returns the length of the sequence. Some built-in sequence types arelist
,str
,tuple
, andbytes
.