Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

python 3.x - Removing multiple elements from a list

In this program I have entered the elements of a list and have to find the second highest element,to achieve that I have created a separate list with the same values of original list,removed the highest element,sort in descending order and print the first element. However,the highest element is 95 and occurs twice in the list but by using the following code, only one 95 gets removed from the list

marks_list2 = marks_list
high = float(max(marks_list))
for j in marks_list:
    if j==high:
        marks_list2.remove(j)
marks_list2.sort(reverse=True)
print('The second highest element is:',marks_list2[0])

Can anyone help me rectify the code and also tell me where I went wrong with my logic. Thanks in advance!

question from:https://stackoverflow.com/questions/65858312/removing-multiple-elements-from-a-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The python built in set() method removes all the repetitions.

marks_list = set(marks_list)
marks_list.remove(max(marks_list))
print('The second highest element is: %s' % max(marks_list))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...