Python – 删除给定索引的元素后打印列表

Python – 删除给定索引的元素后打印列表

Python语言是处理数据最强大的编程语言。列表是Python中可用的不同类型的数据结构之一。列表可以容纳不同数据对象(如整数、字符串甚至浮点数类型)的元素。一旦分配给列表的值不能后期更改。列表中的元素是通过索引值来识别的,在本文中,我们将讨论通过指定索引来删除元素的方法。

在给定索引处删除元素后打印列表

列表由元素组成,索引值从0开始,到指定的元素数为止。列表中的元素删除可以通过图示来解释。有不同的方法可用于删除元素。下面给出的列表包含7个元素,第一行表示元素的索引值,第二行包含元素的值。

Python - 删除给定索引的元素后打印列表

删除索引处为“3”的元素

要删除元素,我们需要找到列表数组的第三个索引,即“56”。在删除指定元素之后,新的列表如下所示,

Python - 删除给定索引的元素后打印列表

方法

  • 方法1 – 使用pop()函数

  • 方法2 – 使用numpy模块

  • 方法3 – 使用reduce方法

方法1:使用pop()函数在给定索引处删除元素后打印列表的Python程序

以上方法简单地借助pop()函数从列表中删除元素。以下代码可用于通过将pop()函数替换为del()函数来删除元素。在使用remove()方法时,元素是通过直接将元素作为参数传递给函数来删除的。

算法

  • 步骤1 - 创建列表以保存整数、字符串和浮点数值,并将其赋值给名为list1的变量。

  • 步骤2 - 使用pop()函数删除索引为2和0的元素。

  • 步骤3 - 最后,print函数返回新的列表。

示例

#initializing the list with set of elements
list1 = [10, 20, 30, 'Hello ', 67.9]
#The pop function will simply remove the element for the mentioned index value
#index value of 2 and 0 needs to be removed
list1.pop(2)
list1.pop(0)
#print function will return the list after removing the elements.
print(list1)

输出

[20, 'Hello ', 67.9]

方法二:使用numpy模块打印删除给定索引处元素后的列表的Python程序

当数据集较大时,可以使用简单的方法来删除元素,我们可以切换到相应模块的内置函数。在这种情况下,使用numpy模块。

算法

  • 步骤1: ‚àí 删除元素所需的模块是numpy,这里声明为‚Äúnp‚Äù。

  • 步骤2: ‚àí 创建带有整数、字符串和浮点数的列表数据结构。

  • 步骤3: ‚àí 要使用numpy模块删除元素,需要将给定的列表转换为numpy数组。

  • 步骤4: ‚àí 将转换后的numpy数组存储在名为‚Äúval‚Äù的变量中。

  • 步骤5: ‚àí 当指定索引值时,使用np.delete()函数从numpy数组中删除元素。

  • 步骤6: ‚àí 然后将上述函数声明为新变量,并打印新的列表。

例子

#importing the module as np
import numpy as np
#Creating a list to hold values of different data types
list1 = [10, 20, 30, 'Hello ', 67.9]
#To convert the list data structure to numpy array and stored in val
val = np.array(list1)
#The given index value elements are removed.
#The delete function has two parameters 
newlist = np.delete(val, [0,2])
#Then finally returns the new list
print(newlist)

输出

['20' 'Hello ' '67.9']

方法三:使用reduce方法打印移除给定索引处元素的列表的Python程序

使用functools模块中的reduce函数可以从列表中移除元素。

算法

  • 步骤1 - 从functools模块导入reduce方法

  • 步骤2 - 创建一个包含元素列表的列表

  • 步骤3 - 使用lambda函数,这是一个匿名函数,不需要定义

  • 步骤4 - 打印语句返回移除索引为0和2的元素后的列表

例子

#importing the module
from functools import reduce
#Creating a list to hold values of different data types
list1 = [10, 20, 30, 'Hello ', 67.9]
#The elements removed using reduce method with key parameters.
new_list = reduce(lambda a,b: a+[b] if list1.index(b) not in [0,2] else a, list1, [])
#Then finally returns the new list
print(new_list)

输出结果

[20, 'Hello ', 67.9]

结论

该组织必须处理大量数据集,因此删除不需要的元素可以使工作更高效、更容易。借助Python语言,通过使用del、remove、pop、numpy模块和functools模块,可以实现从列表中删除元素。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程