Discuss / Python / 打卡

打卡

Topic source

雅乐landa

#1 Created at ... [Delete] [Delete and Lock User]

#tuple放入dict:

>>> t=(1,2,3)

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}

>>> d[t]=63

>>> d

{'Michael': 95, 'Bob': 75, 'Tracy': 85, (1, 2, 3): 63}

>>> d[1]=t

>>> d

{'Michael': 95, 'Bob': 75, 'Tracy': 85, (1, 2, 3): 63, 1: (1, 2, 3)}

>>> t=(1,[2,3])

>>> d[t]=32

Traceback (most recent call last):  File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'

>>> d[2]=t

>>> d

{'Michael': 95, 'Bob': 75, 'Tracy': 85, (1, 2, 3): 63, 1: (1, 2, 3), 2: (1, [2, 3])}

#tuple放入set:

>>> s

{2, 3, 4}

>>> t

(1, [2, 3])

>>> s.add(t)

Traceback (most recent call last):  File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'

>>> t=(1,2,3)

>>> s.add(t)

>>> s

{2, 3, 4, (1, 2, 3)}

腻害!

1. 分别把“可变”tuple(含list的tuple)和不可变的tuple放入dict的key和value:

可变tuple放入dict的key显示非法hash的key;不可变tapule正常放入。

2. 把可变tuple(含list的tuple)和不可变tuple放入set:

可变tuple不可放入set(无法判断是否和已有元素相同);不可变tuple放入set正常。

>>> s

{2, 3, 4}

>>> t

(1, [2, 3])

请问这个是创建set和tuple吗?有点不懂

harmonyVivi

#5 Created at ... [Delete] [Delete and Lock User]

>>> s

{2, 3, 4}

>>> t

(1, [2, 3])

第一个就是创建set,第二个应该是创建的数组不是tuple

付知妤

#6 Created at ... [Delete] [Delete and Lock User]

记住要点。set中的元素都是不可变的,dict中的key都是不可变的即可。

(1, [2, 3]) 这个是一个可变的tuple吧。


  • 1

Reply