Discuss / Python / 我的理解

我的理解

Topic source

丶胡卜

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

set需要一个list来当提供集合 格式就是

s = set([1,2,3])

传入的方式是list,但是list是一个可变对象 所以这样

s = set([1,2,3],[4,5,6])

就会报错

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: set expected at most 1 arguments, got 2

因为set无法判断两个可变对象是否相等,也无法确定set中是否有相同的元素,所以set不能放入其他的list

把(1, 2, 3)和(1, [2, 3])放入dict或set中 dict

t1 = (1,2,3)
t2 = (1,[2,3])
d = ['one':12,'two':34,'three':56]
d [t1] = 78
d
{'three': 56, 'one': 12, 'two': 34, (1, 2, 3): 78}

如果填入t2就会报错

d [t2] =78
d
raceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

因为t2里面含有list所以报错,得出dict中key不能为list 再来set

t1
(1, 2, 3)
t2
(1, [2, 3])
s = set([1,2,3])
s.add(t1)
s
{1, 2, 3, (1, 2, 3)}

这里是可行的因为t1里面没有包含list t2

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

同样报错了因为set与dict原理是相同的同样不能键入list 只是没有value只有key

声明字典的时候用{},第三行笔误[].


  • 1

Reply