Python比较两个列表

时间:2010-10-03 01:59:30

标签: python-3.x python

您好我想比较两个这样的列表

a = [1,2] b = 10,20] 如果a中的每个元素都是>,则compare(a,b)将返回True。 b中的对应元素

所以比较([1,2]> [3,4])是真的

比较([1,20]> [3,4])是假的

了解pythonic方式

干杯

2 个答案:

答案 0 :(得分:10)

使用zip

len(a) == len(b) and all(j > i for i, j in zip(a, b))

答案 1 :(得分:1)

我不确定你在寻找什么,因为你的例子中显示的结果似乎与你所说的你想要归还的内容相矛盾,如果两个列表的长度不相等或者两者兼而有,你也没有说明你想要什么是空的。

由于这些原因,我的答案明确处理了大部分条件,因此您可以轻松更改它以满足您的需求。我还将比较作为谓词函数,因此也可以改变。特别注意最后三个测试用例。

顺便说一下,如果所有他的隐含假设都是正确的话,@ Axike 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
相关问题