Skip to main content
 首页 » 编程设计

python之你能解释一下这个 Python 列表理解吗

2025年05月04日12bonelee

def get_max(r, a, b): 
    """ Returns the maximum value in the form (index, value). """ 
    return max([(x+a, r[a:b][x]) for x in xrange(len(r[a:b]))], key=lambda x:x[1]) 

谁能解释一下这个列表推导式的作用?

请您参考如下方法:

为了提高效率,最好避免一遍又一遍地重复 r 的切片

chunk = r[a:b] 
[(x+a, chunk[x]) for x in xrange(len(chunk))] 

我认为这也使代码的含义更加清晰(它不完全是 Pythonic)

chunk = r[a:b] 
[(i, j) for i, j in enumerate(chunk, a)] 

哦,这是身份列表理解

list(enumerate(chunk, a)) 

所以你可以说

def get_max(r, a, b): 
    """ Returns the maximum value in the form (index, value). """ 
    return max(enumerate(r[a:b], a), key=lambda x:x[1]) 

正如@vonPetrushev 试图在评论中解释的那样,您可以用 itemgetter 替换 lambda 函数。

from operator import itemgetter 
def get_max(r, a, b): 
    """ Returns the maximum value in the form (index, value). """ 
    return max(enumerate(r[a:b], a), key=itemgetter(1)) 

没有太大的性能差异,itemgetter 版本更具描述性(只要您知道 itemgetter 的作用)