Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 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 Answer

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...