空集文字?

[] =空list html

() =空tuple python

{} =空dict ide

set是否有相似的符號? 仍是我必須寫set()spa


#1樓

這取決於您是否要使用文字進行比較或賦值。 code

若是要使現有集合爲空,則能夠使用.clear()方法,尤爲是要避免建立新對象時。 若是要進行比較,請使用set()或檢查長度是否爲0。 htm

例: 對象

#create a new set    
a=set([1,2,3,'foo','bar'])
#or, using a literal:
a={1,2,3,'foo','bar'}

#create an empty set
a=set()
#or, use the clear method
a.clear()

#comparison to a new blank set
if a==set():
    #do something

#length-checking comparison
if len(a)==0:
    #do something

#2樓

只是爲了擴展公認的答案: unicode

2.7版和3.1版開始,python已以用法{1,2,3}形式set文字{} {1,2,3} ,但{}自己仍用於空字典。 get

Python 2.7(第一行在Python <2.7中無效) it

>>> {1,2,3}.__class__
<type 'set'>
>>> {}.__class__
<type 'dict'>

Python 3.x

>>> {1,4,5}.__class__
<class 'set'>
>>> {}.__class__
<type 'dict'>

此處更多內容: https//docs.python.org/3/whatsnew/2.7.html#other-language-changes


#3樓

更加瘋狂的想法:在Python 3接受unicode標識符的狀況下,您能夠聲明一個變量ϕ = frozenset() (ϕ爲U + 03D5),而後改用它。


#4樓

必定要使用 set()建立一個空集。

可是,若是您想打動別人,請告訴他們您能夠使用文字和*經過Python> = 3.5( 請參閱PEP 448 )建立一個空集,方法是:

>>> s = {*()}  # or {*{}} or {*[]}
>>> print(s)
set()

這基本上是一種更簡潔的方法, {_ for _ in ()} ,可是不要這樣作。


#5樓

是。 適用於非空dict / set的相同表示法適用於空dict / set。

注意非空dictset文字之間的區別:

{1: 'a', 2: 'b', 3: 'c'} -數字鍵-值對內部使一個dict
{'aaa', 'bbb', 'ccc'} -內部的值元組組成一個set

因此:

{} ==零個鍵值對==空dict
{*()} ==空元組==空set

可是事實是您能夠作到,但這並不意味着您應該這樣作。 除非您有很強的理由,不然最好顯式構造一個空集,例如:

a = set()

注意 :正如評論中注意到的那樣, {()} 不是空集。 這是一個包含1個元素的集合:空元組。

相關文章
相關標籤/搜索