Python 比较两个列表
你好,我想比较两个列表,像这样:
a=[1,2] b=[10,20]
如果列表a中的每个元素都大于列表b中对应的元素,compare(a,b)就会返回True。
比如,compare([1,2] > [3,4])会返回True。
而compare([1,20] > [3,4])则会返回False。
请问用Python的方式怎么实现这个呢?
谢谢!
2 个回答
1
我不太确定你想要什么,因为你例子中的结果似乎和你说的想要的结果相矛盾。而且你也没有说明如果两个列表的长度不一样或者都为空时应该怎么处理。
所以,我的回答特别考虑了这些情况,这样你可以很容易地根据自己的需要进行修改。我还把比较的部分做成了一个函数,这样你也可以根据需要进行调整。特别注意最后三个测试案例。
顺便说一下,@Mike Axiak 的回答很好,如果他的隐含假设都是正确的话。
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
10
使用 zip 函数:
len(a) == len(b) and all(j > i for i, j in zip(a, b))