Discuss / Python / 关于set

关于set

Topic source

Agoni52Hz_

#1 Created at ... [Delete] [Delete and Lock User]
s = set(([1,2,3]))print(s)

Traceback (most recent call last):
  File "C:/work/day3.py", line 12, in <module>
    s.sort()
AttributeError: 'set' object has no attribute 'sort'


s = set(((1,2,3)))s.add(4)print(s)

{1, 2, 3, 4}

s = set(((1,2,3),1))s.add(4)print(s)

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

set()括号内仅需要一个集合(也可以是元素)可以是元组也可以是列表,但是列表或元组内的元素的元素必须是不可变的所以列表或元组内的元素可以是int str 以及tuple都可以 因为他们是固定的 不可变的 但不能是list 因为list可变  可参考上面出错  可是我不是太能理解第二种和第三种的原因

 key=[1,2,3]

>>> d[key]=1

Traceback (most recent call last):

  File "<pyshell#23>", line 1, in <module>

    d[key]=1

TypeError: unhashable type: 'list'

key=[1,2,3]

>>> s=set(key)

>>> s

{1, 2, 3}

这样看set和dic有些不同啊,key都是列表,dic报错,set就没问题

俗人范

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

s = set ([key])

这样就报错了。

你的code不报错是因为你是把[1,2,3]放进set,而不是key这个list


  • 1

Reply