Python is used to obtain the smallest elements in a sequence.

Source: Internet
Author: User

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'

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.