1. 程式人生 > >Python3基礎之(三十 四)set 找不同

Python3基礎之(三十 四)set 找不同

一、set 基本

Set 最主要的功能就是尋找一個句子或者一個 list 當中不同的元素.

>>> list=['1','1','2','3','2','4']
>>> print(set(list))
{'1', '3', '2', '4'}
>>> sentence='wlecome to my hometown'
>>> print(set(sentence))
{' ', 'n', 'c', 'o', 'm', 'y', 'l', 'w', 't', 'e', 'h'}
>>
>list_1=['1','1','2','3','2','4'] >>>sentence='welcome to mu hometown' >>>print(set(list_1+list(sentence))) {'t', 'n', 'l', 'w', 'm', 'e', 'c', 'o', '3', ' ', 'u', '1', '2', 'h', '4'}

二、新增元素

定義好一個 set 之後我們還可以對其新增需要的元素, 使用 add 就能新增某個元素. 但是不是每一個東西都能新增, 比如一個列表.

list_1=['1','1'
,'2','3','2','4'] list_2=set(list_1) list_2.add('x') print(set(list_2))
    {'1', 'x', '4', '3', '2'}

例如:新增列表會報錯

list_1=['1','1','2','3','2','4']
list_2=set(list_1)
list_2.add(['x','y'])
print(set(list_2))

報錯

Traceback (most recent call last):
  File "D:/Users/hupo/PycharmProjects/pro1/test/test2.py"
, line 3, in <module> list_2.add(['x','y']) TypeError: unhashable type: 'list'

三、清除元素或 set

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

>>> list_1=['1','1','2','3','2','4']
>>> list_2=set(list_1)
>>> print(list_2)
{'3', '2', '4', '1'}
>>> list_2.remove('3')
>>> print(list_2)
{'2', '4', '1'}
>>> list_2.discard('4')
>>> print(list_2)
{'2', '1'}
>>> list_2.clear()
>>> print(list_2)
set()

四、篩選操作

我們還能進行一些篩選操作, 比如對比另一個東西, 看看原來的set 裡有沒有和他不同的 (difference). 或者對比另一個東西, 看看 set 裡有沒有相同的 (intersection).

>>> list_1=['1','1','2','3','2','4']
>>> list_2=set(list_1)
>>> list_2
{'3', '2', '4', '1'}
>>> list_2.difference({'2','3'})
{'4', '1'}
>>> list_2.intersection('4','6','12')
set()
>>> list_2
{'3', '2', '4', '1'}
>>> list_2.intersection({'4','3','12'})
{'3', '4'}