python中set()函数的用法、参数实例讲解

python的set()函数

在python的源码之中,有这么一句话:Build an unordered collection of unique elements,意思就是通过python的set()函数可以构建一个无序的独一无二(元素去重)的元素集合。而且去重也是set()函数的一个常用用法。


set()函数的参数类型

  • set() -> new empty set object:参数为空时,生成一个空的集合对象;
  • set(iterable) -> new set object:参数为可迭代对象时,生成一个新的集合对象;

set()函数的实例代码

>>> set() #无参数时,生成空的集合
set() #因为集合跟字典dict的符号一样,也是用花括号“{}”(如下面实例),所以用set()来表示空的集合大概就是为了与空的字典区分开来
>>> set('') #参数为空字符串
set()
>>> set('abc') #参数为字符串
{'b', 'a', 'c'}
>>> set([1,2,3]) #参数为list列表
{1, 2, 3}
>>> set((1,2,3,2,2)) #参数为有重复元素的元组,set()函数将会去掉重复的
{1, 2, 3}
>>> set({'a':5,'b':6}) #参数为字典
{'b', 'a'}
>>> set(1) #参数为int对象时,python将抛出TypeError,后面的not iterable更是说明参数应当为可迭代对象
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.