Using code examples to demonstrate the use of list-building in Python

Source: Internet
Author: User
1 Square List

If you want to create a list of squares that contain 1 to 10, you can do this:

Squares = []for x in Range]: Squares.append (x**2)

This is a simple example, but using a list-generated formula can create this list more succinctly.

Squares = [x**2 for x in range (10)]

The simplest list generation begins with square brackets, with an expression inside the square brackets followed by a for statement. List generation always returns a list.

2 List of numbers divisible by 3

Usually, you might write:

numbers = []for x in range: if x% 3 = = 0:  numbers.append (x)

You can include an if statement in the List Builder to conditionally add items to the list. To create a list of numbers between 0 and 100 that can be divisible by 3, you can use a list deduction:

numbers = [x for x in range] if x% 3 = = 0]

3 Finding prime numbers

This is usually done using several lines of code.

Noprimes = []for i in range (2, 8): for J in range (I*2, i):  noprimes.append (j) primes = []for x in Range (2): if X not in Noprimes:  primes.append (x)

However, you can simplify your code by using two list-generation.

Noprimes = [J for I in Range (2, 8) for J in range (I*2, A, i)]primes = [x for x in range (2, +) if x not in Noprimes]

The first line of code uses a multi-layer for loop in a list generation. The first loop is the outer loop, and the second loop is the inner loop. To find prime numbers, we first find a list of non-prime numbers. This non-qualitative list is produced by finding multiples of 2-7. Then we loop through the numbers and see if each number is in a non-qualitative list.

FIX: As Shoyer on Reddit points out, using the set to find Noprimes (the attribute parameter in the code, the translator's note) is more efficient. Since noprimes should only contain unique values, and we frequently check to see if a value exists, we should use the collection. The use syntax of a collection is similar to that of a list, so we can use it like this:

Noprimes = Set (j for I in Range (2, 8) for J in range (i*2,, i)) primes = [x for x in range (2, +) if x not in Noprimes]

4 Nested list dimensionality reduction

Suppose you have a list of lists (the list contains lists) or a matrix,

Matrix = [[0,1,2,3], [4,5,6,7], [8,9,10,11]

And you want to dimension it to a one-dimensional list. You can do this:

flattened = []for row in Matrix:for i in row:  flattened.append (i)

To use the list-generated formula:

flattened = [I for row in the matrix for I in row]

This uses two for loops to iterate over the entire matrix. The outer (first) loop iterates by row, and the inner (second) loop iterates over each item of the row.

5 simulating multiple coin toss events

Suppose you need to simulate a coin toss event, where 0 is the front and 1 is the reverse, and you can write code like this:

From random import randomresults = []for x in Range]: results.append (int (round (random)))

Or use a list-building to make your code more concise:

From random import randomresults = [Int (round ())) for X in range (10)]

This uses the Range function to loop 10 times. Each time we rounded the output of the random (). Because the random () function returns a 0 to 1 floating-point number, rounding the output returns 0 or 1. The Round () function returns a floating-point data, using an int () to convert it to an integral type and add it to the list.

6 remove vowels in a sentence

Suppose you have a sentence,

Sentence = ' Your mother was a hamster '

And you want to remove all the vowel letters. We can easily do this with a few lines of code:

vowels = ' aeiou ' non_list = []for l in Sentence:if no l in vowels:  non_list.append (l) nonvowels = '. Join (Non_list)

Or you can simplify it by using a list-generation:

vowels = ' aeiou ' nonvowels = '. Join ([L for L in sentence if not l in vowels])

This example uses list generation to create an alphabetical list of letters from the non-vowel letters of the sentence sentence. We then pass the generated list to the join () function to convert to a string.

FIX: As Iamadogwhatisthis on Reddit, this example does not require a list-generation. Using the generator (generator) is better:

vowels = ' aeiou ' nonvowels = '. Join (L for L in sentence if not l in vowels)

Note that the square brackets are removed here. This is because the join function receives any data that can be iterated, including the list or generator. This syntax without square brackets uses the generator. This produces the same result (as a list generation), and the generator produces the corresponding entry when we traverse it, as opposed to wrapping all the items together as a list. This allows us to not have to save the entire list to memory, and this is more efficient for processing large amounts of data.

7 getting the list of file names in the directory

The following code will traverse through the files in the My_dir directory and append each txt-suffix file name to files.

Import osfiles = []for f in Os.listdir ('./my_dir '): If F.endswith ('. txt '):  files.append (f)

This can also be used to simplify the code using a list-generation:

Import Osfiles = [F for f in Os.listdir ('./my_dir ') if F.endswith ('. txt ')]

Or you can get a list of relative paths:

Import osfiles = [Os.path.join ('./my_dir ', F) for F in Os.listdir ('./my_dir ') if F.endswith ('. txt ')]

Thanks to Reddit on the RASBT offer.

8 reading a CSV file as a dictionary list

We often need to read and process data from CSV files. One of the most useful ways to work with CSV data is to convert it to a list of dictionaries.

Import CSVData = []for x in CSV. Dictreader (Open (' file.csv ', ' RU ')): Data.append (x)

You can use list generation to quickly implement:

Import CSVData = [x for x in CSV. Dictreader (Open (' file.csv ', ' RU '))]

The Dictreader class will automatically use the first line of the CSV file as the key property name for the dictionary. The Dictreader class returns an object that will traverse all the rows of the CSV file. This file object is generated by the open () function. We provide open () two parameters – the first is the CSV file name and the second is the pattern. In this case, ' RU ' has two meanings. As usual, ' r ' means to open the file in read mode. ' U ' indicates that we will accept generic newline characters – ' n ', ' R ' and ' RN '.

Thanks to Reddit on the BLACWIDONSFW offer.

  • 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.