Re: [问题] 集合 set 问题

楼主: Hsins (翔)   2019-07-16 10:56:17
※ 引述《h0304 (h0304)》之铭言:
: 但我一直想不通 为何这2个结果会不一样
: 1. s={'Hello'}
: print(s)
: => {'Hello'}
s = { 'Hello' }
这边是把 'Hello' 这个字串物件放入 set 里作为一个元素
: 2. s=set ('Hello')
: print(s)
: => {'o','l','e','H'}
s = set('Hello')
这边是把 'Hello' 这个字串物件拆分之后的元素放入 set 里
: 这两种都是宣告s为集合 , 2种 print (type(s)) 都是 <class 'set'>
: 为何第1种不会拆解文字,但第2种会拆解文字 ?
https://docs.python.org/3.7/library/stdtypes.html#set
The constructors for both classes work the same:
class set([iterable])
class frozenset([iterable])
Return a new set or frozenset object whose elements are taken from iterable.
The elements of a set must be hashable. To represent sets of sets, the inner
sets must be frozenset objects. If iterable is not specified, a new empty set
is returned.
所以你 set() 里面是不能放非 iterable 的物件的

Links booklink

Contact Us: admin [ a t ] ucptt.com