Python怎么实现删除列表中最大元素和最小元素,需要用到什么函数吗

2021-04-19 18:15发布

3条回答
studentaaa
2楼 · 2021-04-25 22:31

python中关于删除list中的某个元素,一般有三种方法:remove、pop、del:

1.remove: 删除单个元素,删除首个符合条件的元素,按值删除
举例说明:

>>> str=[1,2,3,4,5,2,6]>>> str.remove(2)>>> str

[1, 3, 4, 5, 2, 6]

 

2.pop: 删除单个或多个元素,按位删除(根据索引删除)

>>> str=[0,1,2,3,4,5,6]>>> str.pop(1) #pop删除时会返回被删除的元素>>> str

[0, 2, 3, 4, 5, 6]

 

>>> str2=['abc','bcd','dce']>>> str2.pop(2)

'dce'
>>> str2
['abc', 'bcd']

 

3.del:它是根据索引(元素所在位置)来删除
举例说明:

>>> str=[1,2,3,4,5,2,6]>>> del str[1]>>> str

[1, 3, 4, 5, 2, 6]

 

>>> str2=['abc','bcd','dce']>>> del str2[1]>>> str2

['abc', 'dce']

 

除此之外,del还可以删除指定范围内的值。

>>> str=[0,1,2,3,4,5,6]>>> del str[2:4] #删除从第2个元素开始,到第4个为止的元素(但是不包括尾部元素)>>> str

[0, 1, 4, 5, 6]

 

del 也可以删除整个数据对象(列表、集合等)

>>> str=[0,1,2,3,4,5,6]>>> del str>>> str #删除后,找不到对象

Traceback (most recent call last):
File "", line 1, in
str
NameError: name 'str' is not defined

注意:del是删除引用(变量)而不是删除对象(数据),对象由自动垃圾回收机制(GC)删除。

 

补充: 删除元素的变相方法

复制代码

s1 = (1, 2, 3, 4, 5, 6)
s2 = (2, 3, 5)
s3 = []for i in s1:    if i not in s2:
        s3.append(i)print('s1_1:', s1)
s1 = s3print('s2:', s2)print('s3:', s3)print('s1_2:', s1)
灰机带翅膀
3楼 · 2021-04-25 23:17

方法1:用del 命令删除指定索引号的元素 比如,del score_list[1] #删除索引号为1的元素


方法2:用pop(n) 删除索引号为n的元素,并返回该元素,默认返回最后一个元素 比如,item = score_list.pop(2) #删除索引号为2的元素,并将该元素的值返回,赋给item


方法3:用 remove(x)移除列表中首个值为x的元素 比如,score_list.remove(65) #删除列表中第一个值为65的元素


靓猴一枚
4楼 · 2022-04-24 11:13

有两种方法,

1. By defining a function:

1.通过定义一个函数:

Procedure:

程序:

  1. Define the function name largest_ele and smallest_ele.

    定义函数名largest_ele和smallest_ele。

  2. Pass two arguments in a function (l,n) : l is the list and n is the number of elements.

    在函数(l,n)中传递两个参数: l是列表, n是元素数。

  3. Run the for loop n times

    运行for循环n次

  4. In the loop find the maximum of the given list and append it to another list

    在循环中找到给定列表的最大值,然后将其追加到另一个列表

  5. And after appending to another list remove the maximum element from the list

    在追加到另一个列表后,从列表中删除最大元素

By the inbuilt module heapq module

通过内置模块heapq模块

If you are looking for the N smallest or largest items and N is small compared to the overall size of the collection, these functions provide superior performance.

如果您正在寻找N个最小或最大的项目,并且N与集合的整体大小相比较小,则这些功能可提供卓越的性能。

  1. Import the heapq module

    导入heapq模块

  2. Give the list

    给出清单

  3. Now use the function heapq.nlargest(n,l) and heapq.nsmallest(n,l) from the module to find the largest and the smallest numbers.

    现在,使用模块中的函数heapq.nlargest(n,l)和heapq.nsmallest(n,l)查找最大和最小的数字。

Python code:

Python代码:

# N largest and smallest element in a list 
# by function and by the help of heapq module

#function to find n largest element
def largest_ele(l,n): 
    s=[]
    for i in range(n):
        s.append(max(l)) #append max of list in a new list
        l.remove(max(l)) #remove max of list from the list
    print('by largest_ele function: ',s)


 #function to find n largest element
def smallest_ele(m,n): 
    t=[]
    for i in range(n):
        t.append(min(m))#append min of list in a new list
        m.remove(min(m))#remove min of list from the list
    print('by smallest_ele function: ',t)


l=[2,4,6,8,10]
m=[0,1,2,3,4,5,6]
n=2
largest_ele(l,n)
smallest_ele(m,n)

# using the inbuilt module function 
# heapq.nlargest and heapq.nsmallest
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print('BY heapq.nlargest: ',heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print('BY heapq.nsmallest: ',heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]

Output

输出量

by largest_ele function:  [10, 8]
by smallest_ele function:  [0, 1]
BY heapq.nlargest:  [42, 37, 23]
BY heapq.nsmallest:  [-4, 1, 2]

Note: The nlargest() and nsmallest() functions are most appropriate if you are trying to find a relatively small number of items. If you are simply trying to find the single smallest or largest item (N=1), it is faster to use min() and max().

注意:如果要查找相对较少的项,则nlargest()和nsmallest()函数最合适。 如果您只是想查找单个最小或最大项(N = 1),则使用min()和max()更快。


相关问题推荐

  • 回答 3

    换行。比如,print hello\nworld效果就是helloworld\n就是一个换行符。\是转义的意思,'\n'是换行,'\t'是tab,'\\'是,\ 是在编写程序中句子太长百,人为换行后加上\但print出来是一整行。...

  • 回答 42

    十种常见排序算法一般分为以下几种:(1)非线性时间比较类排序:a. 交换类排序(快速排序、冒泡排序)b. 插入类排序(简单插入排序、希尔排序)c. 选择类排序(简单选择排序、堆排序)d. 归并排序(二路归并排序、多路归并排序)(2)线性时间非比较类排序:...

  • 回答 70
    已采纳

    前景很好,中国正在产业升级,工业机器人和人工智能方面都会是强烈的热点,而且正好是在3~5年以后的时间。难度,肯定高,要求你有创新的思维能力,高数中的微积分、数列等等必须得非常好,软件编程(基础的应用最广泛的语言:C/C++)必须得很好,微电子(数字电...

  • 回答 28

    迭代器与生成器的区别:(1)生成器:生成器本质上就是一个函数,它记住了上一次返回时在函数体中的位置。对生成器函数的第二次(或第n次)调用,跳转到函数上一次挂起的位置。而且记录了程序执行的上下文。生成器不仅记住了它的数据状态,生成器还记住了程序...

  • 回答 9

    python中title( )属于python中字符串函数,返回’标题化‘的字符串,就是单词的开头为大写,其余为小写

  • 回答 6

    第一种解释:代码中的cnt是count的简称,一种电脑计算机内部的数学函数的名字,在Excel办公软件中计算参数列表中的数字项的个数;在数据库( sq| server或者access )中可以用来统计符合条件的数据条数。函数COUNT在计数时,将把数值型的数字计算进去;但是...

  • 回答 1

    head是方法,所以需要取小括号,即dataset.head()显示的则是前5行。data[:, :-1]和data[:, -1]。另外,如果想通过位置取数据,请使用iloc,即dataset.iloc[:, :-1]和dataset.iloc[:, -1],前者表示的是取所有行,但不包括最后一列的数据,结果是个DataFrame。...

  • Python入门简单吗2021-09-23 13:21
    回答 45

    挺简单的,其实课程内容没有我们想象的那么难、像我之前同学,完全零基础,培训了半年,直接出来就工作了,人家还在北京大公司上班,一个月15k,实力老厉害了

  • 回答 4

    Python针对众多的类型,提供了众多的内建函数来处理(内建是相对于导入import来说的,后面学习到包package时,将会介绍),这些内建函数功用在于其往往可对多种类型对象进行类似的操作,即多种类型对象的共有的操作;如果某种操作只对特殊的某一类对象可行,Pyt...

  • 回答 8

     相当于 ... 这里不是注释

  • 回答 4

    还有FIXME

  • 回答 3

    python的两个库:xlrd和xlutils。 xlrd打开excel,但是打开的excel并不能直接写入数据,需要用xlutils主要是复制一份出来,实现后续的写入功能。

  • 回答 8

    单行注释:Python中的单行注释一般是以#开头的,#右边的文字都会被当做解释说明的内容,不会被当做执行的程序。为了保证代码的可读性,一般会在#后面加一两个空格然后在编写解释内容。示例:#  单行注释print(hello world)注释可以放在代码上面也可以放在代...

  • 回答 2

    主要是按行读取,然后就是写出判断逻辑来勘测行是否为注视行,空行,编码行其他的:import linecachefile=open('3_2.txt','r')linecount=len(file.readlines())linecache.getline('3_2.txt',linecount)这样做的过程中发现一个问题,...

  • 回答 4

    或许是里面有没被注释的代码

  • 回答 26

    自学的话要看个人情况,可以先在B站找一下视频看一下

没有解决我的问题,去提问