1. 程式人生 > >集合關系的交集,差,並集的運算

集合關系的交集,差,並集的運算

section amp enc span inter AI pan ron nio

1.交集

r = ["hehe","haha","woaini"]
v = ["hehe","haha","nishishabi"]
p = set(r)
y = set(v)
print(p.intersection(y))
print(p&y)

{hehe, haha}
{hehe, haha}

用intersection或者&都可以

2.並集

r = ["hehe","haha","woaini"]
v = ["hehe","haha","nishishabi"]
p = set(r)
y = set(v)
print(p.union(y))
print(p|y) {haha, hehe, woaini, nishishabi} {haha, hehe, woaini, nishishabi}

用union或者|都可以

3.差集

r = ["hehe","haha","woaini"]
v = ["hehe","haha","nishishabi"]
p = set(r)
y = set(v)
print(p-y)
print(p.difference(y))

{woaini}
{woaini}

用difference或者-都可以

集合關系的交集,差,並集的運算