gpt4 book ai didi

python - 什么类型提示同时包含列表和元组?

转载 作者:太空狗 更新时间:2023-10-29 21:23:35 26 4
gpt4 key购买 nike

我有一个函数可以接受任何可以索引的变量作为输入,例如列表或元组。我如何在函数的类型提示中指出这一点?

最佳答案

您的方法正在接受 sequence , 所以使用 typing.Sequence .这是一个泛型,因此您可以指定序列必须包含的对象类型:

from typing import Sequence

def foo(bar: Sequence[int]):
# bar is a sequence of integers

引用Python glossary :

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.

关于python - 什么类型提示同时包含列表和元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42486006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com