Finding Matching And Nonmatching Items In Lists
Solution 1:
Use set
instead of list
. This way you can do lots of nice things:
set1 = set(['dog', 'cat', 'pig', 'donkey'])
set2 = set(['dog', 'cat', 'donkey'])
matched = set1.intersection(set2) # set(['dog', 'cat', 'donkey'])unmatched = set1.symmetric_difference(set2) # set(['pig'])
I know it's not exactly what you asked for, but it's usually a better practice to use sets instead of lists when doing this sort of things.
More on sets here: http://docs.python.org/library/stdtypes.html#set
Solution 2:
use the following code.
listt3=[]
for i in listt1:
if i in listt2:
listt3.append(1)
else:
listt3.append(0)
If you prefer one-liners,
listt3=[ 1 if i in listt2 else 0 for i in listt1]
Solution 3:
Here is how I would do it if list2
is short:
list1 = ['dog', 'cat', 'pig', 'donkey']
list2 = ['dog', 'cat', 'donkey']
list3 = [int(val in list2) for val in list1]
print(list3)
This prints:
[1, 1, 0, 1]
If list2
is long, you could convert it to a set
first to make the code more efficient:
list1 = ['dog', 'cat', 'pig', 'donkey']
set2 = set(['dog', 'cat', 'donkey'])
list3 = [int(valin set2) forvalin list1]
print(list3)
The reason your current code produces too many elements is that you call append()
on every iteration of the inner loop, and there are len(List1) * len(List2)
such iterations.
Here is how it can be fixed:
defmatch_nonmatch(List1, List2):
List3 = []
for i inrange(len(List1)):
for j inrange(len(List2)):
if List1[i] == List2[j]:
List3.append(1)
break# fix #1else: # fix #2
List3.append(0)
return List3
Note the added break
and the fact that the else
clause is now refers to the inner for
and not the if
.
That said, I'd still use the one-liner at the top of my answer.
Solution 4:
You can use bitwise operation too:
List1 = ['dog', 'cat', 'pig', 'donkey']
List2 = ['dog', 'cat', 'donkey']
matching:
set(List1) & set(List2)
not matching:
set(List1) ^ set(List2)
Solution 5:
>>> list1 = ['dog', 'cat', 'pig', 'donkey']; list2 = ['dog', 'cat', 'donkey']
>>> [i in list2 for i in list1]
[True, True, False, True]
Also, you should read PEP8, CamelCase names are commonly used for classes only.
Post a Comment for "Finding Matching And Nonmatching Items In Lists"