Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何创建返回列表包含字符串的类型提示?_Python_Python 3.5_Type Hinting - Fatal编程技术网

Python 如何创建返回列表包含字符串的类型提示?

Python 如何创建返回列表包含字符串的类型提示?,python,python-3.5,type-hinting,Python,Python 3.5,Type Hinting,我想在Python程序中使用类型提示。如何为复杂的数据结构创建类型提示,如 带字符串的列表 返回整数的生成器 示例 def names() -> list: # I would like to specify that the list contains strings? return ['Amelie', 'John', 'Carmen'] def numbers(): # Which type should I specify for `numbers()

我想在Python程序中使用类型提示。如何为复杂的数据结构创建类型提示,如

  • 带字符串的列表
  • 返回整数的生成器
示例

def names() -> list:
    # I would like to specify that the list contains strings?
    return ['Amelie', 'John', 'Carmen']

def numbers():
    # Which type should I specify for `numbers()`?
    for num in range(100):
        yield num    
使用;它包含泛型和类型对象,可用于指定容器及其内容的约束:

import typing

def names() -> typing.List[str]:  # list object with strings
    return ['Amelie', 'John', 'Carmen']

def numbers() -> typing.Iterator[int]:  # iterator yielding integers
    for num in range(100):
        yield num
根据您如何设计代码以及希望如何使用
names()
的返回值,您也可以在此处使用和类型,具体取决于您是否希望能够改变结果

生成器是一种特定类型的迭代器,因此
类型化。迭代器在这里是合适的。如果生成器也接受
send()
值并使用
return
设置
StopIteration
值,则也可以使用:

如果你是新的类型暗示,那么可能会有所帮助

def filtered_numbers(filter) -> typing.Generator[int, int, float]:
    # contrived generator that filters numbers; returns percentage filtered.
    # first send a limit!
    matched = 0
    limit = yield
    yield  # one more yield to pause after sending
    for num in range(limit):
        if filter(num):
            yield num
            matched += 1
    return (matched / limit) * 100