Python learning-How to filter data based on criteria in lists, dictionaries, and collections

Source: Internet
Author: User

Check out the Python official documentation version 3.6 prior to learning about the following knowledge.

1, Range (start,stop,step) function. Start defaults to 0,step to take a number every few steps.

List[range (5)]=[0,1,2,3,4]

The integer within the generated range. List[range (1,5)]=[1,2,3,4]

List[range (1,5,2)]=[1,3]

2, Randint (b) generates a random integer between a B (including a B). A=randint (3,6) a=3|4|5|6

3. generate a list with a length of 10, where the range of each element in the list is between-10, and 10

Data=[randint ( -10,10) for X in range (10)]

I. Filtering the data in a list

1. Filtering function filter (function, list) filter (lambda x:x>=0,data)

2. List parsing [x for x in Data if x>=0] This method is more efficient and short.

Second, filter the data in the dictionary

Generates a random dictionary dict={x:randint (70,100) for x in range (1,11)} key (1-10), and value is a random number between 70 and 100.

{1:82, 2:87, 3:96, 4:74, 5:73, 6:93, 7:73, 8:84, 9:77, 10:100}

{k:v for k,v in Dict.items () if v>=90} (using the Items method in Python3, Python2 with the Iteritems method)

Third, filter the data in the collection

Generates a set s={x for X in range (10)}

Filter {x for x in S if x>6}

Python learning-How to filter data based on criteria in lists, dictionaries, and collections

Related Article

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.