Python - 删除非增加元素
给定一个列表,我们的任务是编写一个Python程序,从列表中删除所有非递增元素。
Input : test_list = [5, 3, 4, 5, 7, 3, 9, 10, 3, 10, 12, 13, 3, 16, 1]
Output : [5, 5, 5, 7, 9, 10, 10, 12, 13, 16]
Explanation : 3, 4 are omitted as 5, (greater element) had occurred before them. Applies to all other omitted elements.
Input : test_list = [5, 3, 4, 5, 7, 3, 9]
Output : [5, 5, 5, 7, 9]
Explanation : 3, 4 are omitted as 5, (greater element) had occurred before them. Applies to all other omitted elements.
方法#1:使用循环
在这种情况下,在填充进一步列表之前检查前一个元素,如果找到更大的元素,则将其附加,否则使用循环删除。
Python3
# Python3 code to demonstrate working of
# Remove non-increasing elements
# Using loop
# initializing list
test_list = [5, 3, 4, 5, 7, 3, 9, 10, 3, 10, 12, 13, 3, 16, 1]
# printing original list
print("The original list is : " + str(test_list))
res = [test_list[0]]
for ele in test_list:
# checking preceeding element to decide for greater element
if ele >= res[-1]:
res.append(ele)
# printing result
print("The list after removing non-increasing elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Remove non-increasing elements
# Using list comprehension + max + zip() + accumulate
from itertools import accumulate
# initializing list
test_list = [5, 3, 4, 5, 7, 3, 9, 10, 3, 10, 12, 13, 3, 16, 1]
# printing original list
print("The original list is : " + str(test_list))
# checking for each element with curr maximum computed using zip
res = [idx for idx, ele in zip(test_list, accumulate(test_list, max)) if idx == ele]
# printing result
print("The list after removing non-increasing elements : " + str(res))
输出:
The original list is : [5, 3, 4, 5, 7, 3, 9, 10, 3, 10, 12, 13, 3, 16, 1]
The list after removing non-increasing elements : [5, 5, 5, 7, 9, 10, 10, 12, 13, 16]
方法 #2:使用列表理解+ max + zip () +累加
在这种情况下,最大元素被压缩到当前元素,然后使用列表理解来检查是否出现比当前元素更高的元素,如果是,则添加它,否则在运行时迭代的结果中忽略新元素。
蟒蛇3
# Python3 code to demonstrate working of
# Remove non-increasing elements
# Using list comprehension + max + zip() + accumulate
from itertools import accumulate
# initializing list
test_list = [5, 3, 4, 5, 7, 3, 9, 10, 3, 10, 12, 13, 3, 16, 1]
# printing original list
print("The original list is : " + str(test_list))
# checking for each element with curr maximum computed using zip
res = [idx for idx, ele in zip(test_list, accumulate(test_list, max)) if idx == ele]
# printing result
print("The list after removing non-increasing elements : " + str(res))
输出:
The original list is : [5, 3, 4, 5, 7, 3, 9, 10, 3, 10, 12, 13, 3, 16, 1]
The list after removing non-increasing elements : [5, 5, 5, 7, 9, 10, 10, 12, 13, 16]