Empty Set Literal

Empty set literal?

No, there's no literal syntax for the empty set. You have to write set().

How to initialize a set and print an empty set {} in python?

set() is correct. It is printed as set() instead of {} to distinguish it from a dict.

A short way to print a set as {} if it is empty might be something like this:

x = set()
print(x or '{}')

Thus:

>>> x = set()
>>> print(x or '{}')
{}
>>> x.add(5)
>>> print(x or '{}')
{5}

Empty Set literal syntax

There isn't one, use Set(Char).new.

Set literals, such as Set{'a'} actually compile to:

__tmp_var = Set(typeof('a')).new
__tmp_var << 'a'
__tmp_var

so there's no performance benefit to using an empty literal instead of Set(Char).new

Creating an empty set

You can just construct a set:

>>> s = set()

will do the job.

Create Empty Set in Python: TypeError: 'dict' object is not callable

Unfortunately foo = set() is the right way to declare empty set in both python 2 and python 3.

I guess you have a set = {} in the former lines.

You can try print(type(set)) to check it.

Pandas - Reading empty set from CSV using literal_eval

Use Series.replace before converting to sets:

df['words'] = df['words'].replace('set()','{}').apply(literal_eval)
df['tags'] = df['tags'].apply(literal_eval)

print (df)
id words tags
0 A {Jude, -, Drawings} []
1 B {mafalda} []
2 C {} []
3 D {Sidestepping, flood} [mountain]
4 E {jack, visvim} []
5 F {} []

EDIT:

def repl(x):
try:
return literal_eval(x.replace('set()','{}'))
except:
return np.nan

df['words'] = df['words'].apply(repl)
df['tags'] = df['tags'].apply(repl)

print (df)
id words tags
0 A {Jude, -, Drawings} []
1 B {mafalda} []
2 C {} []
3 D {Sidestepping, flood} [mountain]
4 E {jack, visvim} []
5 F {} []
6 -G NaN NaN


Related Topics



Leave a reply



Submit