查找部分子集 python
Finding partial subsets python
我正在寻找一种方法来获取一个 set
中出现在另一个 set
中的元素数量。
鉴于这两组:
a = 'a b c d'
b = 'a b c e f'
a = set(a.split())
b = set(b.split())
这会打印出错误:
print a.issubset(b) # prints False
由于 a
的三个元素出现在 b
中,是否有一种 pythonic 方式来代替打印“3”?
IIUC,可以使用set.intersection
:
>>> a.issubset(b)
False
>>> a.intersection(b)
{'a', 'c', 'b'}
>>> len(a.intersection(b))
3
可以缩写为&
,因为a
和b
都是集合:
>>> len(a & b)
3
你可以 &
和 |
在 python 个集合上执行简单的集合代数。
例如:
> a & b
set(['a', 'c', 'b'])
> a | b
set(['a', 'c', 'b', 'e', 'd', 'f'])
我正在寻找一种方法来获取一个 set
中出现在另一个 set
中的元素数量。
鉴于这两组:
a = 'a b c d'
b = 'a b c e f'
a = set(a.split())
b = set(b.split())
这会打印出错误:
print a.issubset(b) # prints False
由于 a
的三个元素出现在 b
中,是否有一种 pythonic 方式来代替打印“3”?
IIUC,可以使用set.intersection
:
>>> a.issubset(b)
False
>>> a.intersection(b)
{'a', 'c', 'b'}
>>> len(a.intersection(b))
3
可以缩写为&
,因为a
和b
都是集合:
>>> len(a & b)
3
你可以 &
和 |
在 python 个集合上执行简单的集合代数。
例如:
> a & b
set(['a', 'c', 'b'])
> a | b
set(['a', 'c', 'b', 'e', 'd', 'f'])