Python列表理解与额外的变量记录?

时间:2018-08-29 08:56:34

标签: python algorithm list-comprehension

我想通过列表理解来做以下事情,这可能吗?

# find the max i + lst[i] in a list, where i is the index and record both the index and the value
lst = [4,3,2,1,1,1]

val, idx = 0,0
for i in range(len(lst)):
    if lst[i] + i > val:
        val = lst[i] + i
        idx = i

# in list comprehension I am only able to find max value, is there a way to find both? 
mx = max([i + lst[i] for i in lst])

1 个答案:

答案 0 :(得分:2)

以下将输出一个最大值的元组和最大值所在的索引:

print(max([(i + n, i) for i, n in enumerate(lst)]))

这将输出:(6, 5)