Python 内置函数

Python set() 函数用于创建集合(无序、去重),或把可迭代对象转集合。

语法

set(iterable)

参数

iterable:可迭代对象。省略则创建空集合。

返回值

返回新集合 set(无序、自动去重)。元素必须可哈希。

示例

print(set())              # set(),空集合
print(set("hello"))       # {'h','e','l','o'},字符去重
print(set([1, 2, 2, 3]))  # {1, 2, 3},去重

nums = [1, 2, 2, 3, 3, 3]
unique = list(set(nums))  # 去重列表
print(unique)             # [1, 2, 3]

输出:

set()
{'h', 'e', 'l', 'o'}
{1, 2, 3}
[1, 2, 3]

注意事项

空集合用 set(),{} 是空字典。集合无序,别依赖顺序。集合里的元素必须可哈希。