问题
[]
= empty list
()
= empty tuple
{}
= empty dict
Is there a similar notation for an empty set
?
Or do I have to write set()
?
回答1:
No, there's no literal syntax for the empty set. You have to write set()
.
回答2:
Just to extend the accepted answer:
From version 2.7
and 3.1
python has got set
literal {}
in form of usage {1,2,3}
, but {}
itself still used for empty dict.
Python 2.7 (first line is invalid in Python <2.7)
>>> {1,2,3}.__class__
<type 'set'>
>>> {}.__class__
<type 'dict'>
Python 3.x
>>> {1,4,5}.__class__
<class 'set'>
>>> {}.__class__
<type 'dict'>
More here: https://docs.python.org/3/whatsnew/2.7.html#other-language-changes
回答3:
By all means, please use set()
to create an empty set.
But, if you want to impress people, tell them that you can create an empty set using literals and *
with Python >= 3.5 (see PEP 448) by doing:
>>> s = {*()} # or {*{}} or {*[]}
>>> print(s)
set()
this is basically a more condensed way of doing {_ for _ in ()}
, but, don't do this.
回答4:
It depends on if you want the literal for a comparison, or for assignment.
If you want to make an existing set empty, you can use the .clear()
metod, especially if you want to avoid creating a new object. If you want to do a comparison, use set()
or check if the length is 0.
example:
#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
回答5:
Adding to the crazy ideas: with Python 3 accepting unicode identifiers, you could declare a variable ϕ = frozenset()
(ϕ is U+03D5) and use it instead.
回答6:
Yes. The same notation that works for non-empty dict/set works for empty ones.
Notice the difference between non-empty dict
and set
literals:
{1: 'a', 2: 'b', 3: 'c'}
-- a number of key-value pairs inside makes a dict
{'aaa', 'bbb', 'ccc'}
-- a tuple of values inside makes a set
So:
{}
== zero number of key-value pairs == empty dict
{*()}
== empty tuple of values == empty set
However the fact, that you can do it, doesn't mean you should. Unless you have some strong reasons, it's better to construct an empty set explicitly, like:
a = set()
NB: As ctrueden noticed in comments, {()}
is not an empty set. It's a set with 1 element: empty tuple.
来源:https://stackoverflow.com/questions/6130374/empty-set-literal