Python基础——set函数

1.set基本用法

Set 最主要的功能就是寻找一个句子或者一个 list 当中不同的元素.

list_ = ['t','h','i','s','i','s','a','l','i','s','t']
print(set(list_))

sentence = 'Today is a sunny day!'
print(set(sentence))
print(list(sentence))     #用list将句子变成list_一样的格式,此时还没有去重

print(set(list_ + list(sentence)))    #两个list合并后再去重

#输出
{'h', 'l', 't', 'i', 's', 'a'}
{'n', 'd', 'i', 'y', 'o', 'u', 's', '!', 'a', 'T', ' '}
['T', 'o', 'd', 'a', 'y', ' ', 'i', 's', ' ', 'a', ' ', 's', 'u', 'n', 'n', 'y', ' ', 'd', 'a', 'y', '!']
{'h', 'n', 'l', 'd', 't', 'i', 'y', 'o', 'u', 's', '!', 'a', 'T', ' '}

2.向set后的列表添加元素

定义好一个 set 之后我们还可以对其添加需要的元素, 使用 add 就能添加某个元素. 但是不是每一个东西都能添加, 比如一个列表.

list_ = ['t','h','i','s','i','s','a','l','i','s','t']
char_set = set(list_)

char_set.add('w')   #注意:只能增加一个,增加一个列表则会报错
print(char_set)

#输出
{'h', 'l', 't', 'i', 'w', 's', 'a'}

3.删除元素

清除一个元素可以用 remove 或者 discard, 而清除全部可以用 clear.

3.1.remove()

char_set.remove('s')
print(char_set)

#输出
{'i', 't', 'w', 'a', 'h', 'l'}

3.2.discard()

char_set.discard('h')
print(char_set)

#输出
{'i', 't', 'w', 'a', 'l'}

3.3.clear()

char_set.clear()
print(char_set)

#输出
set()      #表示为空

4.比较两个集合

4.1.difference()

我们还能进行一些筛选操作, 比如对比另一个东西, 看看原来的 set 里有没有和他不同的 (difference).

list_ = ['t','h','i','s','i','s','a','l','i','s','t']
set_1 = set(list_)
set_2 = {'h','e','l','l','o'}

print(set_1)
print(set_2)
print('\n')
print("difference:",set_1.difference(set_2))  #打印set_1中有而set_2中没有的

#输出
{'i', 't', 'a', 'h', 's', 'l'}
{'h', 'o', 'l', 'e'}


difference: {'i', 's', 't', 'a'}

4.2.intersection()

对比另一个东西, 看看 set 里有没有相同的 (intersection).

list_ = ['t','h','i','s','i','s','a','l','i','s','t']
set_1 = set(list_)
set_2 = {'h','e','l','l','o'}

print(set_1)
print(set_2)
print('\n')
print("intersection:",set_1.intersection(set_2))    #打印set_1与set_2相同的部分

#输出
{'i', 't', 'a', 'h', 's', 'l'}
{'h', 'o', 'l', 'e'}


intersection: {'h', 'l'}
发布了173 篇原创文章 · 获赞 507 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_37763870/article/details/105135851