I have a set which contains elements like
(1,2,"r"), (1,2,"d"), (1,3,"p")
I am only interested in the number of distinct (x,y) pairs like in the above it will be 2. How do I
calculate that using python?
Sounds like a one-liner will suffice (supposing your set is a list
of tuples
, referenced by variable name l
):
l = [YOUR LIST OF TUPLES]
len(set([t[:2] for t in l]))
NB : the above treats the pair (x,y)
as distinct from (y,x)
; if (x,y)
and (y,x)
are intended to be treated as indistinct, then use:
len(set([frozenset(t[:2]) for t in l]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.