gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:50:54 24 4
gpt4 key购买 nike

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

# 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])

最佳答案

下面将输出最大值的元组和最大值出现的索引:

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

输出:(6, 5)

关于记录了额外变量的 Python 列表理解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52073395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com