📜  Python - 删除非增加元素

📅  最后修改于: 2022-05-13 01:54:38.913000             🧑  作者: Mango

Python - 删除非增加元素

给定一个列表,我们的任务是编写一个Python程序,从列表中删除所有非递增元素。

方法#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))


输出:

方法 #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))

输出: