Python学习笔记_8:set 函数的使用方法

前面我们介绍了python的列表,元组,dict。

set就是我们所说的集合

今天介绍一下set 函数的基本用法:

1、set的使用方法

>>> I = set([3,5,2,1,4])
>>> print(I)
{1, 2, 3, 4, 5}
%set会自动将数字排序

2、set自动合并相同元素

>>> I = set([5,2,3,5,2])
>>> print(I)
{2,3,5}

3、集合中元素是无序的

>>> I = set([1,2,3,4,5])
>>> I[1]
%%就会报错
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    I[1]
TypeError: 'set' object does not support indexing

4、集合 set 增减元素

>>> I.add(5)
>>> I
{1, 2, 3, 4, 5}
>>> I.remove(5)
>>> I
{1, 2, 3, 4}
发布了27 篇原创文章 · 获赞 59 · 访问量 7367

猜你喜欢

转载自blog.csdn.net/qq_45504119/article/details/104713450