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

SoI*_*ins 3 python comparison performance list

我想在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.
Run Code Online (Sandbox Code Playgroud)

我想我可以像下面的块一样编写代码,但我不知道它是否最有效.我的程序将调用这个方法很多,所以我想尽可能地简化这个.

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)
Run Code Online (Sandbox Code Playgroud)

它是否已经得到了它的好处(n的大O),或者是否有更快的方法(或者使用系统功能的方式)?

澄清:我希望返回"无"的情况最常发生,因此这很重要.

KCh*_*oux 5

你熟悉这个奇妙的zip功能吗?

import itertools

def compare(xs, ys):
  all_less = True
  all_greater = True

  for x, y in itertools.izip(xs, ys):
    if not all_less and not all_greater:
      return None
    if x > y:
      all_less = False
    elif x < y:
      all_greater = False

  if all_less:
    return "list 1 is <= list 2"
  elif all_greater:
    return "list 1 is >= list 2"
  return None  # all_greater might be set False on final iteration
Run Code Online (Sandbox Code Playgroud)

邮编需要两个列表(xsys在这种情况下,但拨打任何你希望他们)和元组序列产生的迭代器.

izip([1,2,3,4], [4,3,2,1]) == [(1,4), (2,3), (3,2), (4,1)]
Run Code Online (Sandbox Code Playgroud)

这样,您可以同时迭代两个列表并串联比较每个值.时间复杂度应为O(n),其中n是列表的大小.

在没有满足> =或<=条件的情况下,它将提前返回.

更新

正如James Matta指出的那样,itertools.izip表现优于zipPython 2中的标准.在Python 3中并非如此,其中标准的zip工作方式izip与旧版本相同.


Aco*_*rbe 5

您可以考虑基于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
Run Code Online (Sandbox Code Playgroud)

显然,你可以设计得到答案的东西.

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!"
Run Code Online (Sandbox Code Playgroud)

每种类型的比较<, >, <=, >=,都可以做到.