主頁 > 後端開發 > Python基本資料型別-list-tuple-dict-set詳解

Python基本資料型別-list-tuple-dict-set詳解

2020-09-24 10:01:56 後端開發

Python基本資料型別-list-tuple-dict-set

資料型別 表示方法 特性
list 串列用方括號表示:[] list是一種有序的集合,可以隨時添加和洗掉其中的元素,和C++陣列的區別就是型別可不同,
tuple 元組用圓括號表示:() 和list相比唯一的差異在于元組是只讀的,不能修改,
dict 字典用花括號表示:{} 串列是有序的物件結合,字典是無序的物件集合,兩者之間的區別在于:字典當中的元素是通過鍵來存取的,而不是通過偏移存取,
set set() 集合是一個無序不重復元素集,基本功能包括關系測驗和消除重復元素

串列list

初始化串列

指定元素初始化串列

>>> num=['aa','bb','cc',1,2,3]
>>> print num
['aa', 'bb', 'cc', 1, 2, 3]

從字串初始化串列

>>> a='oiawoidhoawd97192048f'
>>> num=list(a)
>>> print num
['o', 'i', 'a', 'w', 'o', 'i', 'd', 'h', 'o', 'a', 'w', 'd', '9', '7', '1', '9', '2', '0', '4', '8', 'f']

從元組初始化串列

>>> a=(1,2,3,4,5,6,7,8)
>>> num=list(a)
>>> print num

創建一個空串列

>>> num=[]
>>> print num
[]

用某個固定值初始化串列

>>> initial_value=https://www.cnblogs.com/CHLL55/p/0
>>> list_length=5
>>> sample_list=[initial_value]*list_length
>>> print sample_list
[0, 0, 0, 0, 0]
>>> sample_list=[initial_value for i in range(10)]
>>> print sample_list
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

訪問串列

訪問單個元素

>>> num=[0,1,2,3,4,5,6,7]
>>> num[3]
3
>>> num=[0,1,2,3,4,5,6,7]
>>> num[0]
0
>>> num[-1]
7
>>> num[-3]
5

遍歷整個串列

num=[0,1,2,3,4,5,6,7]
for a in num:
    print a,

for i in range(len(num)):
    print num[i],

輸出結果:0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7

串列操作

更新串列

>>> num=[0,1,2,3,4,5,6,7]
>>> num[1]='abc'
>>> print num
[0, 'abc', 2, 3, 4, 5, 6, 7]

洗掉串列元素

num=[0,1,2,3,4,5,6,7]
for i in range(len(num)):
    print num[i],
del num[2]
print num

輸出結果:0 1 2 3 4 5 6 7 [0, 1, 3, 4, 5, 6, 7]

串列運算子+*

串列對+和的運算子與字串相似,+號用于組合串列,號用于重復串列,

以下為+運算子

>>> a=['a','b','c']
>>> b=['d','e','f']
>>> c=a+b
>>> print c
['a', 'b', 'c', 'd', 'e', 'f']

以下為*運算子

>>> a=['a','b','c']
>>> c=a*4
>>> print c
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

串列函式

以下是串列相關函式的分類

串列分類

xmind檔案可點這里下載

以下是help(list)的結果中關于重點函式的介紹部分

Help on list object:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |  
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |  
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -> None -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

元組tuple

Python的元組與串列類似,不同之處在于元組的元素不能修改;元組使用小括號(),串列使用方括號[];元組創建很簡單,只需要在括號中添加元素,并使用逗號(,)隔開即可,

元組初始化

>>> t = (1, 2, 3)
>>> print(t)
(0, 1, 2)
>>> t = tuple(range(3))
>>> print(t)
(0, 1, 2)

元組函式

關于tuple相關的函式可以使用help命令獲得,

help(tuple)
Help on class tuple in module builtins:

class tuple(object)
 |  tuple() -> empty tuple
 |  tuple(iterable) -> tuple initialized from iterable's items
 |  
 |  If the argument is a tuple, the return value is the same object.
 |  
 |  Methods defined here:
 |  
 |  count(...)
 |      T.count(value) -> integer -- return number of occurrences of value
 |  
 |  index(...)
 |      T.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.

list和index方法的使用和list一模一樣,

命名元組

Python有一個類似tuple的容器namedtuples(命名元組),位于collection模塊中,namedtuple是繼承自tuple的子類,可創建一個和tuple類似的物件,而且物件擁有可訪問的屬性,

在c/c++中,對應的資料型別是結構體struct,

struct Point//宣告一個結構體型別Point,代表一個點
{
    int x;  //包括一個整型變數x
    int y;  //包括一個整型變數y
};  //最后有一個分號

這樣就宣告了一個新的結構體型別Point,有了型別就可以定義結構體的變數了,

Point p1,p2;

在c/c++中結構體的最大作用在于組織資料,也就是對資料的封裝(可以把結構體理解為特殊的類),在python中起相同作用的就是命名元組了,命名元祖的具體使用如下

>>> from collections import namedtuple	#依賴collections包的namedtuple模塊
>>> Point = namedtuple('Point', 'x,y')
>>> p1 = Point(11, y=22)
>>> p1
Point(x=11, y=22)
>>> type(p1)
__main__.Point
>>> p1.x
11
>>> p1.y
22
>>> p1[0] + p1[1]
33
>>> a, b = p1
>>> a, b
(11, 22)

命名元祖的具體使用可以參見:namedtuple()以及python 命名元組

字典dict

字典相關的所有內容如下

字典小結

xmind檔案可點這里下載

help(dict)

可以發現,dict是python內建的類,是一種key-value結構

Help on class dict in module __builtin__:

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)
 |  
 |  Methods defined here:

字典(dictionary)是除串列之外python中最靈活的內置資料結構型別,串列是有序的物件結合,字典是無序的物件集合,兩者之間的區別在于:字典當中的元素是通過鍵來存取的,而不是通過偏移存取,

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'};

每個鍵與值必須用冒號隔開(??,每對用逗號分割,整體放在花括號中({}),鍵必須獨一無二,但值則不必;值可以取任何資料型別,但必須是不可變的,如字串,數或元組,

字典初始化

In [1]: d = {}		#{}被字典占用了,所以set不能按照這個初始化

In [2]: type(d)
Out[2]: dict

In [3]: d = dict()

In [4]: d = {'a':1, 'b':2}

In [5]: d = dict([('a', 1), ('b', 2)])	#可接受以元組為元素的串列

In [6]: d
Out[6]: {'a': 1, 'b': 2}

In [7]: d = dict.fromkeys(range(5))		# 傳入的可迭代元素為key, 值為None

In [8]: d
Out[8]: {0: None, 1: None, 2: None, 3: None, 4: None}

In [9]: d = dict.fromkeys(range(5), 'abc')	# 傳入的可迭代元素為key, 值為'abc'

In [10]: d
Out[10]: {0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc'}

增加

d[key] = value,update

In [10]: d
Out[10]: {0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc'}

In [11]: d['a'] = 1		# 可以直接使用key作為下標, 對某個不存在的下標賦值,會增加kv對

In [12]: d
Out[12]: {0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc', 'a': 1}

In [13]: d.update([('c',3),('p',0)])	# update 傳入的引數需要和dict保持一致

In [14]: d
Out[14]: {0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc', 'p': 0, 'c': 3, 'a': 1}

In [15]: d.update([('c', 4), ('p', 4)])	#對已經存在的update時會進行修改,通常用于合并字典

In [16]: d
Out[16]: {0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc', 'p': 4, 'c': 4, 'a': 1}

洗掉

  • pop 用于從字典洗掉一個key, 并回傳其value,當洗掉不存在的key的時候, 會拋出KeyError,當洗掉不存在的key, 并且指定了默認值時, 不會拋出KeyError, 會回傳默認值
  • popitem 隨機 回傳并洗掉一個kv對的二元組
  • clear 清空一個字典
  • del陳述句
In [16]: d
Out[16]: {0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc', 'p': 4, 'c': 4, 'a': 1}

In [17]: help(d.pop)
Help on built-in function pop:

pop(...) method of builtins.dict instance
    D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
    If key is not found, d is returned if given, otherwise KeyError is raised

In [18]: d.pop(0)	# 洗掉一個key,并且回傳對應的value
Out[18]: 'abc'

In [19]: d
Out[19]: {1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc', 'p': 4, 'c': 4, 'a': 1}

In [20]: d.pop(0)	# 如果要洗掉的key不存在,則拋出KeyError
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-20-e1702b259b84> in <module>()
----> 1 d.pop(0)

KeyError: 0

In [21]: d.pop(0, 'default')	# 如果給定default,則洗掉不存在的key時會回傳default
Out[21]: 'default'

In [22]: d.pop(1, 'default')	# 給定的default對存在的key不會產生影響
Out[22]: 'abc'

In [23]: d
Out[23]: {2: 'abc', 3: 'abc', 4: 'abc', 'p': 4, 'c': 4, 'a': 1}

訪問

單個元素的訪問

  • 通過key直接訪問
  • 通過get函式訪問
In [1]: d = {'r':2, 'd':2, 'c':3, 'p':0}

In [2]: d
Out[2]: {'c': 3, 'd': 2, 'p': 0, 'r': 2}

In [3]: d['p']
Out[3]: 0

In [4]: d['c']
Out[4]: 3

In [5]: d['a']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-5-169a40407b7f> in <module>()
----> 1 d['a']

KeyError: 'a'

In [6]: d.get('d')
Out[6]: 2

In [7]: d.get('a')

In [8]: d.get('a','default')
Out[8]: 'default'

In [9]: help(d.setdefault)


In [10]: d.setdefault('c','default')
Out[10]: 3

In [11]: d.setdefault('a','default')
Out[11]: 'default'

In [12]: d
Out[12]: {'a': 'default', 'c': 3, 'd': 2, 'p': 0, 'r': 2}

字典的遍歷

直接for in遍歷

for x in d:
    print(x)

直接用for in 遍歷字典, 遍歷的是字典的key

keys函式遍歷

  • d.keys() # keys 方法回傳一個可迭代物件, 元素是字典所有的key
  • d.keys() -> dict_keys(['d', 'a', 'c', 'r', 'p'])
for x in d.keys():
	print(x)

values函式遍歷

  • d.values() # values 方法回傳一個可迭代物件,元素是字典所有的value
  • d.values() -> dict_values([2, 'default', 3, 2, 0])
for x in d.values():
	print(x)

items函式遍歷

  • d.items() # items 方法回傳一個可迭代物件, 元素是字典的所有(k, v)對
  • d.items() -> dict_items([('d', 2), ('a', 'default'), ('c', 3), ('r', 2), ('p', 0)])
for x in d.items():
	print(x)

輸出如下

('d', 2)
('a', 'default')
('c', 3)
('r', 2)
('p', 0)

另外一種方式:決議(k,v)對

for k, v in d.items():
	print(k, v)

輸出如下

d 2
a default
c 3
r 2
p 0

keys, values, items 回傳的都類似生成器的物件, 它并不會復制一份記憶體

Python2對應的函式回傳的是串列, 會復制一份記憶體

字典的限制

  • 字典的key不能重復
  • 字典的key需要可hash

默認字典

默認字典是defaultdict

In [25]: from collections import defaultdict

In [26]: d1 = {}

In [27]: d1
Out[27]: {}

In [28]: d2 = defaultdict(list)	# list在此是list的初始化函式

In [29]: d2
Out[29]: defaultdict(list, {})

In [30]: d1['a']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-30-a9ea8faf9ae0> in <module>()
----> 1 d1['a']

KeyError: 'a'

In [31]: d2['a']
Out[31]: []

default初始化的時候, 需要傳入一個工廠函式, 具體的介紹可以使用help(defaultdict)來查看,當我們使用下標訪問一個key的時候, 如果這個key不存在, defaultdict會自動呼叫初始化時傳入的函式, 生成一個物件作為這個key的value,因此上面的list函式初始化的時候就生成了一個空串列,

以下是使用dict和defaultdict的對比

d = {}

for k in range(10):
    for v in range(10):
        if k not in d.keys():
            d[k] = []
        d[k].append(v)

如果這段代碼使用defaultdict來寫

d = defaultdict(list)

for k in range(10):
    for v in range(10):
        d[k].append(v)

有序字典

有序字典是OrderedDict(第一個字母大寫)

In [33]: from collections import OrderedDict

In [34]: d = OrderedDict()

In [35]: d[0] = 3

In [36]: d[3] = 4

In [37]: d[1] = 5

In [38]: d
Out[38]: OrderedDict([(0, 3), (3, 4), (1, 5)])

In [39]: for k, v in d.items():
    ...:     print(k, v)
    ...:     
0 3
3 4
1 5

有序字典會保持插入的順序

集合set

集合相關的所有內容如下

集合小結

xmind檔案可點這里下載

>>> help(set)
Help on class set in module __builtin__:

class set(object)
 |  set() -> new empty set object
 |  set(iterable) -> new set object
 |  
 |  Build an unordered collection of unique elements.
 |  
 |  Methods defined here:

詳細使用可以參考:https://blog.csdn.net/business122/article/details/7541486

下面是一個小例子:

>>> a = [11,22,33,44,11,22]  
>>> b = set(a)  
>>> b  
set([33, 11, 44, 22])  
>>> c = [i for i in b]  
>>> c  
[33, 11, 44, 22]  

定義與初始化

In [2]: s = set()
In [3]: s
Out[3]: set()
In [4]: s = {1, 2, 3}
In [5]: s
Out[5]: {1, 2, 3}
In [6]: s = set(range(3))
In [7]: s
Out[7]: {0, 1, 2}

增加

增加函式有兩個addupdate

add是增加單個元素,和串列的append操作類似,是原地修改

update是增加一個可迭代物件,和串列的extend操作類似,是原地修改

兩個函式對于已經存在的元素會什么也不做

In [7]: s
Out[7]: {0, 1, 2}

In [8]: s.add(3)

In [9]: s
Out[9]: {0, 1, 2, 3}

In [10]: s.add(3)

In [11]: s
Out[11]: {0, 1, 2, 3}

In [12]: help(s.update)
Help on built-in function update:

update(...) method of builtins.set instance
    Update a set with the union of itself and others.

In [13]: s.update(range(4, 7))

In [14]: s
Out[14]: {0, 1, 2, 3, 4, 5, 6}

In [15]: s.update(range(4, 9))

In [16]: s
Out[16]: {0, 1, 2, 3, 4, 5, 6, 7, 8}

洗掉

  • remove 洗掉給定的元素, 元素不存在拋出KeyError(需要拋出例外時使用此函式)
  • discard 洗掉給定的元素, 元素不存在,什么也不做(和remove的唯一區別)
  • pop 隨機arbitrary洗掉一個元素并回傳, 集合為空,拋出KeyError
  • clear 清空集合
In [16]: s
Out[16]: {0, 1, 2, 3, 4, 5, 6, 7, 8}

In [17]: s.remove(0)

In [18]: s
Out[18]: {1, 2, 3, 4, 5, 6, 7, 8}

In [19]: s.remove(10)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-19-99f2b84d3df8> in <module>()
----> 1 s.remove(10)

KeyError: 10


In [21]: s
Out[21]: {1, 3, 4, 5, 6, 7, 8}

In [22]: s.discard(1)

In [23]: s
Out[23]: {3, 4, 5, 6, 7, 8}

In [24]: s.discard(10)

In [25]: s
Out[25]: {3, 4, 5, 6, 7, 8}

In [26]: help(s.pop)
Help on built-in function pop:

pop(...) method of builtins.set instance
    Remove and return an arbitrary(隨機的) set element.
    Raises KeyError if the set is empty.

In [27]: s.pop()
Out[27]: 3

In [28]: s.pop()
Out[28]: 4

In [29]: s.clear()

In [30]: s
Out[30]: set()

In [31]: s.pop()
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-31-e76f41daca5e> in <module>()
----> 1 s.pop()

KeyError: 'pop from an empty set'

修改

集合不能修改單個元素

查找

  • 集合不能通過索引

  • 集合沒有訪問單個元素的方法

  • 集合不是線性結構, 集合元素沒有順序

集合的pop操作的隨機性可以證明集合不是線性結構的,

In [32]: s = {1, 2, 3, 4, 5, 65, 66, 67, 88}

In [33]: s.pop()
Out[33]: 65

成員運算子

  • in
  • not in

用于判斷一個元素是否在容器中

In [34]: 1 in [1, 2, 3, 4]
Out[34]: True

In [35]: 5 in [1, 2, 3, 4]
Out[35]: False

In [36]: 5 not in [1, 2, 3, 4]
Out[36]: True

In [37]: 'love' in 'I love python'
Out[37]: True

In [38]: [1, 2] in [1, 2, 3, 4]
Out[38]: False

In [39]: 1 in (1, 2, ,3 ,4)
  File "<ipython-input-39-ed83805ebe55>", line 1
    1 in (1, 2, ,3 ,4)
                ^
SyntaxError: invalid syntax


In [40]: 1 in (1, 2, 3, 4)
Out[40]: True

In [41]: 1 in {1, 2, 3, 4}
Out[41]: True

集合的成員運算和其他線性結構的時間復雜度不同

In [42]: lst = list(range(100000))

In [43]: s = set(range(100000))

In [44]: %%timeit
    ...: -1 in lst
    ...: 
1000 loops, best of 3: 1.61 ms per loop

In [45]: %%timeit
    ...: -1 in s
    ...: 
The slowest run took 29.72 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 49.3 ns per loop

由以上可見,做成員運算的時候 集合的效率遠高于串列,

In [46]: lst2 = list(range(100))

In [47]: s = set(range(100))

In [48]: %%timeit
    ...: -1 in lst2
    ...: 
1000000 loops, best of 3: 1.6 μs per loop

In [49]: %%timeit
    ...: -1 in s
    ...: 
The slowest run took 20.77 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 56.9 ns per loop

做成員運算時 串列的效率和串列的規模有關,而集合的效率和集合的規模無關,

成員運算:

  • 集合 O(1)
  • 串列(線性結構) O(n)

集合運算

集合運算主要有:交集,差集,對稱差集,并集

python中的集合運算都對應兩個版本,一個默認版本(回傳新的集合),一個update版本(會更新集合本身),

交集

intersection

交集的特性:滿足交換律,多載了&運算子

In [50]: s1 = {1, 2, 3}

In [51]: s2 = {2, 3, 4}

In [52]: s1.intersection(s2)
Out[52]: {2, 3}

In [53]: s2.intersection(s1)		#交集滿足交換律
Out[53]: {2, 3}

In [54]: s1
Out[54]: {1, 2, 3}

In [55]: s2
Out[55]: {2, 3, 4}

In [56]: s1.intersection_update(s2)		
    #交集的update版本,做原地修改,回傳none,相當于  s1 = s1.intersection(s2)

In [57]: s1
Out[57]: {2, 3}

In [58]: s2
Out[58]: {2, 3, 4}

In [59]: s1 = {1, 2, 3}

In [60]: s1 & s2	#交集多載了&運算子,相當于 s1.intersection(s2)
Out[60]: {2, 3}

差集

difference

差集特性:不滿足交換律,多載了-運算子

In [61]: s1 = {1, 2, 3}

In [62]: s2 = {2, 3, 4}

In [63]: s1.difference(s2)
Out[63]: {1}

In [64]: s2.difference(s1)	#差集不滿足交換律
Out[64]: {4}

In [65]: s1.difference_update(s2)	#差集的update版本,相當于  s1 = s1.difference(s2)

In [66]: s1
Out[66]: {1}

In [67]: s1 = {1, 2, 3}

In [68]: s1 - s2	#差集多載了-運算子,相當于  s1.difference(s2)
Out[68]: {1}

In [69]: s2 - s1
Out[69]: {4}

對稱差集

symmetric_difference

對稱差集特性:滿足交換律,多載了^運算子

In [70]: s1 = {1, 2, 3}

In [71]: s2 = {2, 3, 4}

In [72]: s1.symmetric_difference(s2)
Out[72]: {1, 4}

In [73]: s2.symmetric_difference(s1)		#對稱差集滿足交換律
Out[73]: {1, 4}

In [74]: s1.symmetric_difference_update(s2)		
    #對稱差集的update版本,相當于  s1 = s1.symmetric_difference(s2)

In [75]: s1
Out[75]: {1, 4}

In [76]: s1 = {1, 2, 3}

In [77]: s1 ^ s2	#對稱差集多載了^運算子,相當于 s1.symmetric_difference(s2)
Out[77]: {1, 4}

并集

union,update

并集特性:滿足交換律,多載了|運算子

In [78]: s1 = {1, 2, 3}

In [79]: s2 = {2, 3, 4}

In [80]: s1.union(s2)
Out[80]: {1, 2, 3, 4}

In [81]: s2.union(s1)	#并集滿足交換律
Out[81]: {1, 2, 3, 4}

In [82]: s1.update(s2)	#update函式就是并集的update版本,相當于 s1 = s1.update(s2)

In [83]: s1
Out[83]: {1, 2, 3, 4}

In [84]: s1 = {1, 2, 3}

In [85]: s1 + s2	#并集多載的運算子不是+
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-85-1659087814e1> in <module>()
----> 1 s1 + s2

TypeError: unsupported operand type(s) for +: 'set' and 'set'

In [86]: s1 | s2	#并集多載的運算子是|
Out[86]: {1, 2, 3, 4}

集合相關的判斷

issuperset,issubset

isdisjoint:判斷是否兩個集合是否不相交(disjoint),有交集則回傳False,沒有交集則回傳True

In [87]: s1 = {1, 2, 3, 4}

In [88]: s2 = {1, 2}

In [89]: s1.issuperset(s2)		#判斷是否是超集
Out[89]: True

In [90]: s2.issubset(s1)		#判斷是否是子集
Out[90]: True

In [91]: s1.isdisjoint(s2)		#判斷是否不相交
Out[91]: False

In [92]: s1 = {1, 2}

In [93]: s2 = {3, 4}

In [94]: s1.isdisjoint(s2)
Out[94]: True

集合的限制

集合的元素不能是可變的,集合的元素必須可hash

In [95]: {'a', 'b', 'c'}
Out[95]: {'a', 'b', 'c'}

In [96]: {[1, 2, 3]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-96-e7ef34388120> in <module>()
----> 1 {[1, 2, 3]}

TypeError: unhashable type: 'list'

In [97]: {bytearray(b'abc')}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-97-62b530a8195b> in <module>()
----> 1 {bytearray(b'abc')}

TypeError: unhashable type: 'bytearray'

In [98]: {{3, 4}}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-98-47b1c90a198f> in <module>()
----> 1 {{3, 4}}

TypeError: unhashable type: 'set'

In [99]: {(1, 2)}
Out[99]: {(1, 2)}

In [100]: {b'abc'}
Out[100]: {b'abc'}

#hash函式可以直接使用
In [101]: hash(b'abc')
Out[101]: 1955665834644107130

In [102]: hash([1, 2, 3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-102-0b995650570c> in <module>()
----> 1 hash([1, 2, 3])

TypeError: unhashable type: 'list'

參考資料

Python集合(set)型別的操作

python資料型別詳解

Python中的List,Tuple和Dictionary


記得幫我點贊哦!

精心整理了計算機各個方向的從入門、進階、實戰的視頻課程和電子書,按照目錄合理分類,總能找到你需要的學習資料,還在等什么?快去關注下載吧!!!

resource-introduce

念念不忘,必有回響,小伙伴們幫我點個贊吧,非常感謝,

我是職場亮哥,YY高級軟體工程師、四年作業經驗,拒絕咸魚爭當龍頭的斜杠程式員,

聽我說,進步多,程式人生一把梭

如果有幸能幫到你,請幫我點個【贊】,給個關注,如果能順帶評論給個鼓勵,將不勝感激,

職場亮哥文章串列:更多文章

wechat-platform-guide-attention

本人所有文章、回答都與著作權保護平臺有合作,著作權歸職場亮哥所有,未經授權,轉載必究!

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/118174.html

標籤:Python

上一篇:二分類問題續 - 【老魚學tensorflow2】

下一篇:scrapy筆記-通用配置

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more