简体   繁体   English

Python中的set[…]是什么意思

[英]What is the meaning of set[…] in Python

I'm pretty new to programming and python.我对编程和 python 很陌生。

As far as I know, for the initialization of the set function you use set() for an empty set, and {... } to initialize elements as a set.据我所知,对于集合 function 的初始化,您将set()用于空集,并使用{... }将元素初始化为集合。 In an example code, I saw set[X] .在示例代码中,我看到了set[X] What is the meaning of the square brackets used in set?集合中使用的方括号是什么意思?

This is the example code:这是示例代码:

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

It's a type hint , in this example, we use type hint For collections, the type of the collection item is in brackets.这是一个类型提示,在这个例子中,我们使用类型提示对于 collections,集合项的类型在括号中。

Example:例子:

# 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}

This is just a parameterising the functions and variable annotations to say that the function needs two arguments, namely x and y which are of type set (build from A and B respectively) and it returns back a set consisting of tuples built by mixing set[A] set[B]这只是对函数和变量注释进行参数化,以说明 function 需要两个 arguments,即xy ,它们是set类型(分别从 A 和 B 构建),它返回一个由混合集合构建的元组组成的set[A] set[B]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM