gpt4 book ai didi

python - 如何在 Python 中键入提示元素或文字列表?

转载 作者:行者123 更新时间:2023-12-05 04:32:47 24 4
gpt4 key购买 nike

假设我有一个变量 x 和一个值列表 ['a', 'b', 'c']。 x 可以只是 'a' 或 'b' 或 'c' 或这些值的列表,如 ['a', 'b'] 或 ['a', 'c', 'a'] 等。如何在 Python 中为 x 编写类型提示?

最佳答案

您正在寻找 Union :

Union type; Union[X, Y] is equivalent to X | Y and means either X or Y.

例子:

from typing import List
from typing import Union

def func(arg: bool) -> Union[str, List[str]]:
if arg:
x = ['a', 'b', 'c']
else:
x = 'c'

return x


print(type(func(True))) # <class 'list'>
print(type(func(False))) # <class 'str'>

关于python - 如何在 Python 中键入提示元素或文字列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71597909/

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