Python comparing two lists
Hello I wanna compare two lists like this
a=[1,2] b=10,20] compare(a,b) will return True if each e开发者_如何学Clement 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
Use zip:
len(a) == len(b) and all(j > i for i, j in zip(a, b))
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 do 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 sequence lengths
if len(a) > len(b):
return False # second sequence is shorter than first
else:
return True # first sequence is shorter than second
else:
return True # pred() was True for all elements in both
# of the non-empty equal-length sequences
else: # both sequences were empty
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
精彩评论