Reputation: 112
I want to be able to check if one list contains 2 elements of another list (that in total has 3 elements)
e.g:
list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]
if #list2 contains any 2 elements of list1:
print("yes, list 2 contains 2 elements of list 1")
else:
print("no, list 2 does not contain 2 elements of list 1")
Upvotes: 0
Views: 3386
Reputation: 363
This works:
list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]
val = 0
for idx in list1:
for idx2 in list2:
if idx == idx2:
val += 1
if val == 2:
print("yes, list 2 contains 2 elements of list 1")
else:
print("no, list 2 does not contain 2 elements of list 1")
Upvotes: 0
Reputation: 182
list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]
if len(set(list1).intersection(set(list2))) == 2:
print("yes, list 2 contains 2 elements of list 1")
else:
print("no, list 2 does not contain 2 elements of list 1")
The .intersection method takes two sets and finds what is common between them. If what is common between them is 2 elements, then you have what you want.
Upvotes: 0
Reputation: 3211
count = 0
for ele in list2:
if ele in list1:
count += 1
if count == 2:
print ("yes, list 2 contains 2 elements of list 1")
else:
print ("no, list 2 does not contain 2 elements of list 1")
Upvotes: 0
Reputation: 24691
You can use itertools.combinations()
to get all sets of two elements from list2
and see if they're subsets of list1
:
import itertools
if any(set(comb).issubset(set(list1)) for comb in itertools.combinations(list2, 2)):
print("yes, ...")
...
Upvotes: 0
Reputation: 1370
I would use a similar description of the one described in the following question, only this time check the length of the sets intersection: How to find list intersection?
list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]
if len(list(set(a) & set(b))) == 2:
print("yes, list 2 contains 2 elements of list 1")
else:
print("no, list 2 does not contain 2 elements of list 1")
Upvotes: 2
Reputation: 4434
def my_func(list1, list2):
count = 0
for i in list1:
for j in list2:
if(i == j) : count += 1
print(count)
if(count >= 2) : return True
else: return False
list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]
if my_func(list1, list2):#list2 contains any 2 elements of list1:
print("yes, list 2 contains 2 elements of list 1")
else:
print("no, list 2 does not contain 2 elements of list 1")
Upvotes: 0
Reputation: 1000
You could write a function to check the elements in common between the two lists, and after verify if quantity of this elements is equals to 2.
For example:
def intersection(list1, list2):
lst3 = [value for value in list1 if value in list2]
return lst3
list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]
if len(intersection(list1, list2) == 2):
print("yes, list 2 contains 2 elements of list 1")
else:
print("no, list 2 does not contain 2 elements of list 1")
Upvotes: 0