I want to take two lists and find the values that appear in both.
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
would return [5]
, for instance.
I want to take two lists and find the values that appear in both.
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
would return [5]
, for instance.
Not the most efficient one, but by far the most obvious way to do it is:
>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
{5}
if order is significant you can do it with list comprehensions like this:
>>> [i for i, j in zip(a, b) if i == j]
[5]
(only works for equal-sized lists, which order-significance implies).
The easiest way to do that is to use sets:
>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
set([5])
Do you want duplicates? If not maybe you should use sets instead:
>>> set([1, 2, 3, 4, 5]).intersection(set([9, 8, 7, 6, 5]))
set([5])
s = ['a','b','c']
f = ['a','b','d','c']
ss= set(s)
fs =set(f)
print ss.intersection(fs)
set(['a', 'c', 'b'])
print ss.union(fs)
set(['a', 'c', 'b', 'd'])
print ss.union(fs) - ss.intersection(fs)
set(['d'])
Setz' answer seems complicated. Perhaps you would rather do
set(f) - set(s)
:)
I prefer the set based answers, but here's one that works anyway
[x for x in a if x in b]