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/archive/2020/09/24/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}
增加
增加函式有兩個add和update
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
記得幫我點贊哦!
精心整理了計算機各個方向的從入門、進階、實戰的視頻課程和電子書,按照目錄合理分類,總能找到你需要的學習資料,還在等什么?快去關注下載吧!!!

念念不忘,必有回響,小伙伴們幫我點個贊吧,非常感謝,
我是職場亮哥,YY高級軟體工程師、四年作業經驗,拒絕咸魚爭當龍頭的斜杠程式員,
聽我說,進步多,程式人生一把梭
如果有幸能幫到你,請幫我點個【贊】,給個關注,如果能順帶評論給個鼓勵,將不勝感激,
職場亮哥文章串列:更多文章

本人所有文章、回答都與著作權保護平臺有合作,著作權歸職場亮哥所有,未經授權,轉載必究!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/118184.html
標籤:其他
上一篇:一起來讀官方檔案-----SpringIOC(06)
下一篇:java面向物件思想之繼承
