首页 > 解决方案 > Python中set[...]的含义是什么

问题描述

我对编程和 python 很陌生。

据我所知,对于 set 函数的初始化,您使用set()一个空集,并将{ ... }元素初始化为一个集合。在示例代码中,我看到了set[X]. 集合中使用的方括号是什么意思?

这是示例代码:

def example_function(x: set[A], y: set[B]) -> set[tuple[A, B]]:
    res = set()
    for i in x:
        for j in y:
            res.add((i, j))
    return res

标签: pythonalgorithmset

解决方案


它是一个类型提示,在这个例子中,我们使用类型提示来进行集合,集合项的类型在括号中。

例子:

# Python 3.9
# For collections, the type of the collection item is in brackets
int_list: list[int] = [1]
int_set: set[int] = {6, 7}

# Python 3.8 and earlier, the name of the collection type is
# capitalized, and the type is imported from 'typing'

from typing import List, Set, Dict, Tuple, Optional

int_list: List[int] = [1]
int_set: Set[int] = {6, 7}

推荐阅读