Python is used to obtain the smallest elements in a sequence.
This example describes how to obtain the smallest elements in a sequence using python. Share it with you for your reference.
The specific method is as follows:
import heapq import random def issorted(data): data = list(data) heapq.heapify(data) while data: yield heapq.heappop(data) alist = [x for x in range(10)] random.shuffle(alist) print 'the origin list is',alist print 'the min in the list is' for x in issorted(alist): print x,
The program running result is as follows:
the origin list is [2, 3, 4, 9, 8, 5, 1, 6, 0, 7]the min in the list is0 1 2 3 4 5 6 7 8 9
The heapq module and random module. heapq binary tree are used to handle priority sequence problems.
In addition, there is a simpler method:
Print heapq. nsmallest (3, alist) # print out that the minimum three elements in the alist list are the least. If it is a letter, it is compared in alphabetical order.
If you are interested, you can test and run the example in this article. I believe this article will be of some reference value for your learning of Python programming.
There is already a set. I need to perform sequence operations on the elements in it. How to implement this? Python 27
Simple: Use the python list built-in method sort
For example, a = [1, 3, 2]
Then run:
A. sort ()
Print
A = [1, 2, 3]
Or use the python built-in method sorted.
Sorted can specify a comparison method. For more information, see references.
Reference: wiki.python.org/moin/HowTo/Sorting
In a dictionary, python returns the key corresponding to the smallest element.
Assume that the dictionary d is:
D = {'A': '7', 'E': '3', 'D': '8', 'G': '7', 'F ': '1', 'J': '2', 'L': '9', 'w': '4 '}
Then, the key-value pairs corresponding to the smallest element are as follows:
Min (d. items (), key = lambda x: x [1])
Get
('F', '1 ')
The key corresponding to the smallest element of the value is:
Min (d. items (), key = lambda x: x [1]) [0]
'F'