【Python 学习笔记】set operations

what are basic set operations in python?

The union of two sets returns a new set containing all elements that are in either set.

A = {1, 2, 3}
B = {3, 4, 5}
union_set = A | B  # {1, 2, 3, 4, 5}
# or
union_set = A.union(B)  # {1, 2, 3, 4, 5}

The intersection of two sets returns a new set containing all elements that are in both sets.

A = {1, 2, 3}
B = {3, 4, 5}
intersection_set = A & B  # {3}
# or
intersection_set = A.intersection(B)  # {3}

The difference of two sets returns a new set containing elements that are in the first set but not in the second.

A = {1, 2, 3}
B = {3, 4, 5}
difference_set = A - B  # {1, 2}
# or
difference_set = A.difference(B)  # {1, 2}

The symmetric difference of two sets returns a new set containing elements that are in either of the sets, but not in both.

A = {1, 2, 3}
B = {3, 4, 5}
sym_diff_set = A ^ B  # {1, 2, 4, 5}
# or
sym_diff_set = A.symmetric_difference(B)  # {1, 2, 4, 5}

Subset and Superset

A = {1, 2}
B = {1, 2, 3}
is_subset = A <= B  # True
# or
is_subset = A.issubset(B)  # True
A = {1, 2, 3}
B = {1, 2}
is_superset = A >= B  # True
# or
is_superset = A.issuperset(B)  # True

Add an element:

A = {1, 2, 3}
A.add(4)  # A becomes {1, 2, 3, 4}

Remove an element: A.remove(x) (raises KeyError if x is not in the set) or A.discard(x) (does not raise an error if x is not in the set)

A = {1, 2, 3}
A.remove(3)  # A becomes {1, 2}
# or
A.discard(3)  # A becomes {1, 2}

Check membership

A = {1, 2, 3}
is_member = 2 in A  # True

These operations provide powerful tools for working with sets in Python, allowing for complex set-based manipulations and comparisons with simple, concise syntax.

"Answer Generated by OpenAI's ChatGPT"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值