我试图在 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/