Python程序在List中查找减点
给定一个列表,获取列表显示第一个负趋势的元素的索引,即下一个元素 < 当前元素的第一个点。如果没有找到返回-1。
Input : test_list = [3, 6, 8, 9, 12, 5, 18, 1]
Output : 4
Explanation : At 12 -> 5, first decreasing point occurs.
Input : test_list = [3, 9, 12, 5, 18, 1]
Output : 2
Explanation : At 12 -> 5, first decreasing point occurs.
方法#1:使用循环
在这里,我们检查下一个元素是否小于当前元素,在第一次找到它的点上,我们打破循环。
Python3
# Python3 code to demonstrate working of
# Decreasing point in List
# Using loop
# initializing list
test_list = [3, 6, 8, 9, 12, 5, 18, 1]
# printing original list
print("The original list is : " + str(test_list))
res = -1
for idx in range(0, len(test_list) - 1):
# checking for 1st decreasing element
if test_list[idx + 1] < test_list[idx]:
res = idx
break
# printing result
print("Decreasing Point : " + str(res))
Python3
# Python3 code to demonstrate working of
# Decreasing point in List
# Using enumerate() + loop
# initializing list
test_list = [3, 6, 8, 9, 12, 5, 18, 1]
# printing original list
print("The original list is : " + str(test_list))
res = -1
for idx, ele in enumerate(test_list):
# checking for 1st decreasing element
if test_list[idx + 1] < ele:
res = idx
break
# printing result
print("Decreasing Point : " + str(res))
输出:
The original list is : [3, 6, 8, 9, 12, 5, 18, 1]
Decreasing Point : 4
方法 #2:使用enumerate() + 循环
在这里,我们使用 enumerate 同时检查索引和值,与上面类似的方法,不同之处在于单独的索引元素访问。
蟒蛇3
# Python3 code to demonstrate working of
# Decreasing point in List
# Using enumerate() + loop
# initializing list
test_list = [3, 6, 8, 9, 12, 5, 18, 1]
# printing original list
print("The original list is : " + str(test_list))
res = -1
for idx, ele in enumerate(test_list):
# checking for 1st decreasing element
if test_list[idx + 1] < ele:
res = idx
break
# printing result
print("Decreasing Point : " + str(res))
输出:
The original list is : [3, 6, 8, 9, 12, 5, 18, 1]
Decreasing Point : 4