English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python 基础教程

Python 流程控制

Função do Python

Tipos de Dados do Python

Python 文件操作

Python 对象和类

Python 日期和时间

Python 高级知识

Python 参考手册

Python set() 使用方法及示例

Python built-in functions

set()内置函数根据给定的iterable创建Python集。

set()的语法为:

set(iterable)

推荐阅读: Python set(集合)

set()参数

set() 接受一个可选参数:

  • iterable(可选) - 要转换为集合的序列(字符串元组等)或集合(集合,字典等)或迭代器对象。

set()返回值

set() 返回:

  • 如果未传递任何参数,则为空集

  • 由给定的iterable参数构造的集合

Example1:根据字符串,元组,列表和范围创建集合

# 空集
print(set())
# iterable为字符串
print(set('Python'))
# iterable为元组
print(set(('a', 'e', 'i', 'o', 'u')))
# iterable为列表
print(set(['a', 'e', 'i', 'o', 'u']))
# iterable is range
print(set(range(5))

Output result

set()
{'P', 'o', 't', 'n', 'y', 'h'}
{'a', 'o', 'e', 'u', 'i'}
{'a', 'o', 'e', 'u', 'i'}
{0, 1, 2, 3, 4}

Note:We cannot use {} syntax to create an empty set because it will create an empty dictionary. To create an empty set, we use set().

Example2: Create set from another set, dictionary, and frozen set

# From set
print(set({'a', 'e', 'i', 'o', 'u'}))
# From dictionary
print(set({'a':1, 'e': 2, 'i':3, 'o':4, 'u':5))
# From frozen set
frozen_set = frozenset(('a', 'e', 'i', 'o', 'u'))
print(set(frozen_set))

Output result

{'a', 'o', 'i', 'e', 'u'}
{'a', 'o', 'i', 'e', 'u'}
{'a', 'o', 'e', 'u', 'i'}

Example3: Create set for custom iterable

class PrintNumber:
    def __init__(self, max):
        self.max = max
    def __iter__(self):
        self.num = 0
        return self
    def __next__(self):
        if(self.num >= self.max):
            raise StopIteration
        self.num += 1
        return self.num
# print_num is iterable
print_num = PrintNumber(5)
# Create a set
print(set(print_num))

Output result

{1, 2, 3, 4, 5}

Python built-in functions