Python:比较两个整数列表的最有效方法

标签 python performance list comparison

我试图在 Python 2.6 中比较两个整数列表,每个列表的大小都相同。我需要的比较是将列表 1 中的第一项与列表 2 中的第一项进行比较,列表 1 中的第二项与列表 2 中的第二项进行比较,依此类推,如果所有列表项都遵循则返回结果相同的比较标准。它应该表现如下:

list1 = [1,1,1,1]
list2 = [2,1,2,3]
compare(list1,list2) 
# returns a "list 1 is <= list 2" response.

list1 = [4,1,4,3]
list2 = [2,1,2,3]
compare(list1,list2) 
# returns a "list 1 is >= list 2" response.

list1 = [3,2,3,2]
list2 = [1,4,1,4]
compare(list1,list2) 
# returns None— some items in list1 > list2, and some items in list2 > list1.

我想我可以像下面的 block 一样编写代码,但我不知道它是否最有效。我的程序将多次调用此方法,因此我想尽可能地简化它。

def compare(list1,list2):
    gt_found = 0
    lt_found = 0
    for x in range(len(list1)):
        if list1[x] > list2[x]:
            gt_found += 1
        elif list1[x] < list2[x]:        
            lt_found += 1
        if gt_found > 0 and lt_found > 0:
            return None   #(some items >, some items <)
    if gt_found > 0:
        return 1          #(list1 >= list2)
    if lt_found > 0:
        return -1         #(list1 <= list2)
    return 0              #(list1 == list2)

它是否已经达到预期效果(big-O of n),或者是否有更快的方法(或使用系统函数的方法)?

澄清:我预计返回“无”的情况最常发生,因此这很重要。

最佳答案

您可以考虑基于 numpy 的向量化比较。

import numpy as np

a = [1,1,1,2]
b = [2,2,4,3]

all_larger = np.all(np.asarray(b) > np.asarray(a))  # true if b > a holds elementwise

print all_larger

        True

很明显,您可以设计这个东西来获得您的答案。

all_larger = lambda b,a : np.all(np.asarray(b) > np.asarray(a))

if all_larger(b,a):
       print "b > a"
elif all_larger(a,b):
       print "a > b"

else
       print "nothing!"

每种类型的比较,例如 <, >, <=, >=,可以做到。

关于Python:比较两个整数列表的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19282833/

相关文章:

python - cv2.addWeighted 除了一些颜色

java - 如何使用 Retrofit 处理具有相同键 "Value"及其字符串和数组的 JSON 响应

java - 将字符串转换为另一个字符串

python - 为什么 ImportError : No module named 'cv2' error come only for python3?

python - 正则表达式只捕获重复组的最后一次出现

jquery - 大规模定制 Web 应用程序 - 性能问题

c++ - 如何将列表中的所有元素移动到数组或 vector 或其他任何内容

python - RBG 三元组值如何转换为单值?单个值介于 0 到 255 之间。如何将单个值映射到彩色图像?

python - 如何在 Microsoft Azure 中提取 Blob 存储中的 Blob 的上次修改日期

Python:从列表到枚举列表以传递给 lambda reduce 函数