Set#

The set function is defined in the swordfish.data module and returns a Set object. It can convert a Python set into a DolphinDB Set.

Creating Sets#

Create a set using swordfish.set.

# Create an empty set.
sf.set(set(), type="INT")                   # set()

# If type is not specified, a set of type LONG is created by default.
a = sf.set({1,2,3})                         # set(3,2,1)

# Specify type to create a set of type DOUBLE.
b = sf.set({2,3}, type="DOUBLE")            # set(2,3)
b.type                                # DOUBLE

c = sf.set({1,5,8,6}, type="INT")           # set(1,5,8,6)

Operations on Sets#

You can perform intersection, union, difference, and symmetric difference on sets.

  • Intersection (&)

a & c      # set(1)
  • Union (|)

a | c      # set(8,6,5,1,2,3)
  • Sub (-)

a - c      # set(3,2)
c - a      # set(5,6,8)
  • Symmetric Difference (^)

a ^ c      # set(8,6,5,2,3)

Use Python’s in keyword to check whether an element exists in the set.

2 in b          # True
5 in b          # False

Use len() to get the number of elements in the set.

len(a)          # 3
len(b)          # 2

Additionally, Swordfish supports comparing two sets using operators: <, <=, >, >=, ==, !=, and in.

For example, if b is a subset of a, then b <= a.

b<=a          # true
a<=b          # false

Modifying Sets#

Use function.append_ to append set.

# Import swordfish.function module
import swordfish.function as F
# Append one element
F.append_(a, 8)            # set(8,1,2,3)

# Append two elements
F.append_(a, [9,10])       # set(8,1,9,2,10,3)

Use function.erase_ to remove elements from the set.

# Delete one delement
F.erase_(a, 8)            # set(1,9,2,10,3)

# Delete two elements
F.erase_(a, [9,10])       # set(1,2,3)

Use function.clear_ to remove all elements from the set.

F.clear_(b)               # set()