使用Python删除大于特定值的列表元素 您所在的位置:网站首页 python删除列表特定元素 使用Python删除大于特定值的列表元素

使用Python删除大于特定值的列表元素

2023-07-10 14:02| 来源: 网络整理| 查看: 265

使用的方法

以下是用于完成此任务的各种方法 -

使用 remove() 方法使用列表理解使用 filter() 方法和 lambda 函数 方法 1:使用 remove() 方法

remove() 函数(从列表中删除元素的第一次出现)

算法(步骤)

以下是执行所需任务要遵循的算法/步骤。−

创建一个变量来存储输入列表。创建另一个变量来存储另一个输入值。使用 for 循环循环访问输入列表中的每个元素。使用 if 条件语句检查当前元素是否大于指定的输入值。如果条件为 true,则使用 to remove() 函数从列表中删除该当前元素,方法是将其作为参数传递给它。删除大于指定输入值的元素后打印结果列表。 例

以下程序使用 remove() 函数从列表中删除大于指定输入值的元素 −

# input list inputList = [45, 150, 20, 90, 15, 55, 12, 75] # Printing the given list print("The Given list is:", inputList) # input value inputValue = 50 # iterarting through the list for i in inputList: # checking whether the current element is greater than the input value if i > inputValue: # removing that current element from the list if the condition is true inputList.remove(i) # printing the resultant list after removing elements larger than 50 print("Removing elements larger than 50 from the list:\n", inputList)

复制

输出

在执行时,上述程序将生成以下输出 -

The Given list is: [45, 150, 20, 90, 15, 55, 12, 75] Removing elements larger than 50 from the list: [45, 20, 15, 12]

复制

方法 2:使用列表理解 列表理解

当您希望基于现有列表的值构建新列表时,列表推导提供了更短/更简洁的语法。

以下程序使用列表推导式从输入列表中删除大于指定输入值的元素 −

# input list inputList = [45, 150, 20, 90, 15, 55, 12, 75] # Printing the given list print("The Given list is:", inputList) # input value inputValue = 50 # removing elements from a list larger than 50 # by traversing through the list and storing elements # that are having a value less than or equal to the given input value resultList = [k for k in inputList if k


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有