Number of paired item in the list

a = [2,7,9]
b = [[7,9],[1,2],[2,9]]

How many pairs in the list [a]corresponds to a pair of tuples [b] Notice the couple [7,9]and [2,9]in the list [a]. Even if a pair [1,2]contains a digit 2, it is not counted because both digits are not on the list [a]. The return value must be 2, len matching pairs.

len(filter(lambda l:if_in(b,l),a))

Need help creating an if_in function or an easier way to write this function in one. How can I make this function work regardless of size aor b.

+4
source share
2 answers

a set.issuperset, , a superset :

a = [2,7,9]
b = [[7,9],[1,2],[2,9]]


st = set(a)

print(sum(st.issuperset(sub) for sub in b))
2

: , , , a , - a:

In [6]: a = [2,7,9]

In [7]: b = [[7,9],[1,2],[2,9]]

In [8]: st = set(b[0])

In [9]: st.issubset(a)
Out[9]: True
In [10]: st = set(b[1])

In [11]: st.issubset(a)
Out[11]: False

In [13]: st = set(a)

In [13]: st.issuperset(b[0])
Out[13]: True

In [14]: st.issuperset(b[1])
Out[14]: False

, , , a .

+6

a, itertools.combinations(iterable, r). , r .

from itertools import combinations

a = [2, 7, 9]
b = [(7, 9), (1, 2), (2, 9)]  
# combinations returns a collection of tuples
# so changed your b items to tuples.

len(filter(lambda x: x in b, combinations(a ,2))
0

Source: https://habr.com/ru/post/1618123/


All Articles