Convert them to sets and use the intersection.
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
Actually there are many ways to solve this, but here would be an example for a beginning student. Study it and try to understand it ...
a = [4,5,6]
b = [1,3,8,6,7,9]
c = []
for bx in b:
if bx in a:
c.append(bx)
if c:
print "these are the elements of list a that are present in list b:"
print c
else:
print "no elements of list a are in list b"
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
How do you do this when the elements of the list are dictionaries? Using sets won't work in that case. Python complains because dictionaries are not "hashable".
For example, I want a function that will tell me which elements of A are in B (the intersection of the two lists), where:
A=[{},{1:2},{3,4},{10:34}]
B=[{5,6},{1,2},{}]
B is not list of dictionary, it is list of set, so it does not make sense to join them.
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
Are the values for keys same, if so you can just ignore values and do set operations by sets produced from the keys of dictionaries?
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852