Python - 元素最大值直到列表中的当前索引
给定包含元素的列表,如果它是当前索引之前的最大元素,则提取元素。
Input : test_list = [4, 6, 7, 8]
Output : [4, 6, 7, 8]
Explanation : All elements are maximum till their index.
Input : test_list = [6, 7, 3, 6, 8, 7]
Output : [7, 8]
Explanation : 7 and 8 are maximum till their index.
方法#1:使用循环
这是可以执行此任务的蛮力方法。在此,我们运行嵌套循环直到当前索引,如果所有元素都低于当前元素,则递增计数器,如果计数器与当前索引匹配,则表明当前元素在当前索引之前是最大的。
Python3
# Python3 code to demonstrate working of
# Elements Maximum till current index in List
# Using loop
# initializing list
test_list = [3, 5, 2, 6, 7, 9, 3]
# printing original list
print("The original list : " + str(test_list))
# Using loop
res = []
for idx in range(1, len(test_list)):
cnt = 0
# inner loop to count element less than current
for idx2 in range(idx):
if test_list[idx] > test_list[idx2]:
cnt = cnt + 1
if cnt == idx:
res.append(test_list[idx])
# printing result
print("Extracted Maximum elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Elements Maximum till current index in List
# Using max() + list comprehension + list slicing
# initializing list
test_list = [3, 5, 2, 6, 7, 9, 3]
# printing original list
print("The original list : " + str(test_list))
# Using max() + list comprehension + list slicing
# max() used to get if current is current maximum
res = [test_list[idx] for idx in range(
1, len(test_list)) if test_list[idx] > max(test_list[:idx])]
# printing result
print("Extracted Maximum elements : " + str(res))
输出
The original list : [3, 5, 2, 6, 7, 9, 3]
Extracted Maximum elements : [5, 6, 7, 9]
方法 #2:使用 max() + 列表理解 + 列表切片
上述功能的组合可以用来解决这个问题。在此,我们使用 max() 检查当前元素是否大于使用列表切片提取的所有先前元素。
Python3
# Python3 code to demonstrate working of
# Elements Maximum till current index in List
# Using max() + list comprehension + list slicing
# initializing list
test_list = [3, 5, 2, 6, 7, 9, 3]
# printing original list
print("The original list : " + str(test_list))
# Using max() + list comprehension + list slicing
# max() used to get if current is current maximum
res = [test_list[idx] for idx in range(
1, len(test_list)) if test_list[idx] > max(test_list[:idx])]
# printing result
print("Extracted Maximum elements : " + str(res))
输出
The original list : [3, 5, 2, 6, 7, 9, 3]
Extracted Maximum elements : [5, 6, 7, 9]