If you have a list in Python π and you need to find for example the 3 elements that are the must present in the list.
You can do it like this :
Create a list
mylist = [1,2,3,4,4,4,4,5,5,6,7,8,8,8,9]
Create two variables, maxcount is the number N of elements that we are searching.
count = 1
maxcount = 3
Use a while loop to find what we are looking for :
while count <= maxcount:
num = max(set(mylist), key=mylist.count)
print(num)
count+=1
while num in mylist:
mylist.remove(num) #Here we remove the element that was the max
Now the full code:
mylist = [1,2,3,4,4,4,4,5,5,6,7,8,8,8,9]
count = 1
maxcount = 3
while count <= maxcount:
num = max(set(mylist), key=mylist.count)
print(num)
count+=1
while num in mylist:
mylist.remove(num)
Now the result is :
4
8
5
You can even add them to a new list...
Top comments (0)