簡體   English   中英

找到部分子集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

是否有替代打印“3”以來的三個要素一個Python的方式a出現在b

IIUC,你可以使用set.intersection

>>> a.issubset(b)
False
>>> a.intersection(b)
{'a', 'c', 'b'}
>>> len(a.intersection(b))
3

這可以縮寫&因為ab都是集合:

>>> len(a & b)
3

你可以&| 在python集上執行簡單的集合代數。

例如:

> a & b
set(['a', 'c', 'b'])
> a | b
set(['a', 'c', 'b', 'e', 'd', 'f'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM