views:

100

answers:

2

Hello I wanna compare two lists like this

a=[1,2] b=10,20] compare(a,b) will return True if each element in a is > corresponding element in b

so compare( [1,2] > [3,4] ) is True

compare( [1,20] > [3,4] ) is False

hiow to do this the pythonic way

Cheers

+8  A: 

Use zip:

len(a) == len(b) and all(j > i for i, j in zip(a, b))
Mike Axiak
A: 

I'm not exactly sure what you're looking for since the result shown in your example seems to contradict what you said you wanted returned, nor to you specify what is desired if the length of the two lists are unequal or both are empty.

For these reasons, my answer explicitly handles most of those conditions so you can easily change it to suit your needs. I've also made the comparison being done a predicate function, so that can be varied as well. Note especially the last three test cases.

BTW, @Mike Axiak's answer if very good if all his implicit assumptions were correct.

def compare_all(pred, a, b):
    """return True if pred() is True when applied to each
       element in 'a' and its corresponding element in 'b'"""

    def maxlen(a, b): # local function
        maxlen.value = max(len(a), len(b))
        return maxlen.value

    if maxlen(a, b): # one or both sequences are non-empty
        for i in range(maxlen.value):
            try:
                if not pred(a[i], b[i]):
                    return False
            except IndexError: # unequal lengths
                if len(a) > len(b): # no comparable in 2nd sequence
                    return False
                else:
                    return True
        else:
            return True
    else:
        return False

print compare_all(lambda x,y: x>y, [1,2], [3,4])   # False
print compare_all(lambda x,y: x>y, [3,4], [1,2])   # True
print compare_all(lambda x,y: x>y, [3,4], [1,2,3]) # True
print compare_all(lambda x,y: x>y, [3,4,5], [1,2]) # False
print compare_all(lambda x,y: x>y, [], [])         # False
martineau