简体   繁体   中英

Comparing all elements of 2 lists with Python 2

I have 2 lists: a = ['5', '2', '3', '4'] , and b = ['1', '6', '7', '5'] . Using Python 2, how can I compare each list element in a to each element in b ? (ie is a[0] == b[0] , is a[0] == b[1] , etc).

I know that I could just write out numerous if statements, but I hope that there is a more elegant way to do this.

After checking each list element, I want to know how many times a shared value was found (in my example lists above, it would be one time, '5' ).

EDIT: This is not a duplicate, b/ci am comparing two different lists to each other, while the possible duplicate dealt with only 1 list.

The count() method of list may help:

>>> a = ['5', '2', '3', '4']
>>> b = ['1', '6', '7', '5']
>>> for item in a:
...     print item, b.count(item)
... 
5 1
2 0
3 0
4 0

Probably faster for big inputs than eugene y's , as it only needs to iterate over b once,
instead of len(a) times:

from collections import Counter
counts = Counter(b)

for i in a:
    print(i, counts[i])

If you are only concerned with shared values, and not with their positions or counts, convert them to set and use intersection :

>>> a = ['5','2','3','4']
>>> b = ['1','6','7','5']
>>> set(a).intersection(b)
{'5'}

If you want to retain how often the elements appear in the intersection, you can also do an intersection of collections.Counter using &

>>> a = ['5','2','3','4','1','1','6','5']
>>> b = ['1','6','7','5','5']
>>> collections.Counter(a) & collections.Counter(b)
Counter({'5': 2, '1': 1, '6': 1})

Note: This is different from the solution by @GingerPlusPlus in that it is symmetric, ie if 5 is present once in list a and twice in list b , then the shared count will be 1 , not 2 .

def cmp(*lists):
    lists_len_min = list(map(lambda x: len(x), lists))
    if min(lists_len_min) != max(lists_len_min):
        raise Exception("Lists must have equal length")
    iterator = iter(lists)
    last = next(iterator)
    for element in iterator:
        for i, each in enumerate(element):
            #print(i, last[i], each)
            if last[i] != each:
                return False
    else:
        return True

This function can compare as many lists you want with equal length. Just call cmp(list1, list2, list3)

This code will produce list of elements which is consist in both a and b list

a = [1,2,3,4]
b = [2,3,1,7]
c = [e for e in a if e in b]

It might be complex by memory in case if you use big arrays but if you plan to use this data than why not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM