Python 类型提示:对于可以是任何可迭代序列的变量,我应该使用什么?

问题描述 投票:0回答:1

考虑功能:

def mysum(x)->int:
    s = 0
    for i in x:
        s += i
    return s

参数

x
可以是
list[int]
set[int]
,也可以是
d.keys()
,其中d是一个字典,它可以是
range(10)
,以及可能的许多其他序列,其中项目是类型国际。
x
的正确类型提示是什么?

我的Python是3.10+。

python type-hinting
1个回答
0
投票

您可以使用

typing.Iterable

from typing import Iterable

def mysum(x: Iterable[int])->int:
    s = 0
    for i in x:
        s += i
    return s
© www.soinside.com 2019 - 2024. All rights reserved.