gpt4 book ai didi

python - 编写一个名为index_of_smallest 的函数,该函数采用整数列表

转载 作者:太空宇宙 更新时间:2023-11-03 20:33:35 26 4
gpt4 key购买 nike

编写一个名为index_of_smallest的函数,它将整数列表作为参数并返回列表中最小元素的索引。如果列表是空列表,该函数应返回 -1

def index_of_smallest(list1):
if len(list1) == 0:
return -1
smallest_value = list1[0]
smallest_index = 0
for i in range(len(list1)):
if smallest_value >:
smallest_index +=1
return smallest_value

print(index_of_smallest([51, 65, 66, 80, 10, 55]))
#output: 4
print(index_of_smallest([]))
#output: -1

最佳答案

类似这样的事情:

def index_of_smallest(lista):
if len(lista) == 0: return -1
return sorted(enumerate(lista),key=lambda x:x[1])[0][0]

关于python - 编写一个名为index_of_smallest 的函数,该函数采用整数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57317955/

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