Python 定义获取列表中最高产品对的函数

Python 定义获取列表中最高产品对的函数,python,list,func,Python,List,Func,我试图找到一个函数,它给出列表中最高相邻元素对的乘积。对于我的代码 gala = [1, 2, 3, 4, 5] def adjacentElementsProduct(inputArray): for i in range(len(inputArray)): if inputArray[i] * inputArray[i+1] > inputArray[i+1] * inputArray[i+2]: return inputArray[i

我试图找到一个函数,它给出列表中最高相邻元素对的乘积。对于我的代码

gala = [1, 2, 3, 4, 5]
def adjacentElementsProduct(inputArray):
    for i in range(len(inputArray)):
        if inputArray[i] * inputArray[i+1] > inputArray[i+1] * inputArray[i+2]:
            return  inputArray[i] * inputArray[i+1] 
    elif inputArray[i+1] * inputArray[i+2] > inputArray[i] * inputArray[i+1] and inputArray[i+1] * inputArray[i+2] > inputArray[i+2] * inputArray[i+3]:
        return  inputArray[i+1] * inputArray[i+2]
    elif inputArray[i+2] * inputArray[i+3] > inputArray[i+1] * inputArray[i+2] and inputArray[i+2] * inputArray[i+3] > inputArray[i+3] * inputArray[i+4]:
         return  inputArray[i+2] * inputArray[i+3]
    else:
        return inputArray[i+3] * inputArray[i+4] 
return adjacentElementsProduct

adjacentElementsProduct(gala)
这里的输出是20(因为4x5是最高的相邻对)。此函数适用于给定列表,即使我更改了数字及其符号的顺序。但是,如果列表的长度更改,则代码将中断。如果名单是

gala = [1, -6]


我希望函数第一个列表的输出是-6,第二个是35。但是对于这样的列表,我的函数中断了

如果我正确理解了您的问题,我认为您的功能可以简化为:

def adjacentElementsProduct(elm):
   if len(elm) < 2:
       return None
   return max(k*v for k, v in zip(elm, elm[1:]))

如果我正确理解了您的问题,我认为您的功能可以简化为:

def adjacentElementsProduct(elm):
   if len(elm) < 2:
       return None
   return max(k*v for k, v in zip(elm, elm[1:]))

对@ChihebNexus方法的修改:

from operator import mul

def adjacentElementsProduct(elm):
   if len(elm) < 2:
       return None
   return max(map(mul, elm, elm[1:]))
从操作员导入mul
def邻接元素产品(elm):
如果len(elm)<2:
一无所获
返回最大值(映射(mul、elm、elm[1:]))
更简短的版本:

def adjacentElementsProduct(elm):
   return max(map(mul, elm, elm[1:])) if len(elm) < 2 else None
def邻接元素产品(elm):
如果len(elm)<2,则返回max(map(mul,elm,elm[1:]),否则无
还有一个:

from operator import mul
from itertools import starmap

def adjacentElementsProduct(elm):
   if len(elm) < 2:
       return None
   return max(starmap(mul, zip(elm, elm[1:])))
从操作员导入mul
从itertools导入星图
def邻接元素产品(elm):
如果len(elm)<2:
一无所获
返回最大值(星图(mul,zip(elm,elm[1:]))

对@ChihebNexus方法的修改:

from operator import mul

def adjacentElementsProduct(elm):
   if len(elm) < 2:
       return None
   return max(map(mul, elm, elm[1:]))
从操作员导入mul
def邻接元素产品(elm):
如果len(elm)<2:
一无所获
返回最大值(映射(mul、elm、elm[1:]))
更简短的版本:

def adjacentElementsProduct(elm):
   return max(map(mul, elm, elm[1:])) if len(elm) < 2 else None
def邻接元素产品(elm):
如果len(elm)<2,则返回max(map(mul,elm,elm[1:]),否则无
还有一个:

from operator import mul
from itertools import starmap

def adjacentElementsProduct(elm):
   if len(elm) < 2:
       return None
   return max(starmap(mul, zip(elm, elm[1:])))
从操作员导入mul
从itertools导入星图
def邻接元素产品(elm):
如果len(elm)<2:
一无所获
返回最大值(星图(mul,zip(elm,elm[1:]))