Search for matching and non-matching items in lists

I am new to Python and a bit confused about what you can and cannot do with lists. I have two lists that I want to compare and return matching and asymmetric elements in binary format. List1has a constant length, and the length List2is different (but always shorter List1).

For instance:

List1 = ['dog', 'cat', 'pig', 'donkey']
List2 = ['dog', 'cat', 'donkey']

Required Conclusion:

List3 = [1, 1, 0, 1]

The code I have so far is:

def match_nonmatch(List1, List2):
    List3 = []
    for i in range(len(List1)):
        for j in range(len(List2)):
            if List1[i] == List2[j]:
                List3.append(1)
            else:
                List3.append(0)
   return List3

I can return matches when I compare lists, but when I include the else statement above, returning fuzzy numbers, I get a list that is much longer than it should be. For example, when I use a list comparing 60 elements, I get a list containing 3600 elements, not 60.

, - , , , , , .

+5
6

.

listt3=[]

for i in listt1:
    if i in listt2:
        listt3.append(1)
    else:
        listt3.append(0)

,

listt3=[ 1 if i in listt2 else 0 for i in listt1]

+5

set list. , :

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'])

, , , .

: http://docs.python.org/library/stdtypes.html#set

+11

, list2 :

list1 = ['dog', 'cat', 'pig', 'donkey']
list2 = ['dog', 'cat', 'donkey']
list3 = [int(val in list2) for val in list1]
print(list3)

:

[1, 1, 0, 1]

list2 , set, :

list1 = ['dog', 'cat', 'pig', 'donkey']
set2 = set(['dog', 'cat', 'donkey'])
list3 = [int(val in set2) for val in list1]
print(list3)

, , , append() , len(List1) * len(List2) .

:

def match_nonmatch(List1, List2):
    List3 = []
    for i in range(len(List1)):
        for j in range(len(List2)):
            if List1[i] == List2[j]:
                List3.append(1)
                break             # fix #1
        else:                     # fix #2
            List3.append(0)
    return List3

break , else for, if.

, .

+4
>>> list1 = ['dog', 'cat', 'pig', 'donkey']; list2 = ['dog', 'cat', 'donkey']
>>> [i in list2 for i in list1]
[True, True, False, True]

, PEP8, CamelCase .

0
[int(i==j) for i, j in zip(list1, list2)]
0

:

List1 = ['dog', 'cat', 'pig', 'donkey']  
List2 = ['dog', 'cat', 'donkey']  

:

set(List1) & set(List2)   

:

set(List1) ^ set(List2) 
0

All Articles