Show the usage of list-generation in Python by code instances _python

Source: Internet
Author: User
Tags generator in python

1 Square List

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

Squares = [] for
x in range (Ten):
 squares.append (x**2)

This is a simple example, but using a list build allows you to create this list more succinctly.

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

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

2 A list of numbers divisible by 3

Usually, you might write this:

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

You can include an if statement in the list generation to conditionally add items to the list. To create a list of numbers that contain 0 to 100 divisible by 3, you can use the list derivation:

numbers = [x for x in range (m) if x 3 = 0]

3 Find 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 i N Range (2):
 if x not in Noprimes:
  primes.append (x)

However, you can use a two-list generation to simplify your code.

Noprimes = [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 ]

The first line of code uses a multi-tier for loop in a list generation. The first loop is the outer loop, and the second loop is the internal loop. To find prime numbers, we first find a list of non prime numbers. By finding a multiple of 2-7, this list of non-mass numbers is generated. Then we loop through the numbers and see if each number is in the non-mass list.

FIX: As Shoyer on Reddit points out, using a set to find Noprimes (the attribute argument in the code) is more efficient. Since noprimes should contain only unique values, and we frequently check whether a value exists, we should use the collection. The use syntax of the collection is similar to the syntax for using the list, so we can use this:

Noprimes = Set (j for I in Range (2, 8) for J in range (I*2, L))
primes = [x for x in range (2,) if x not in Nopri Mes

4 Nested list dimensionality reduction

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

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

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

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

To use a list-generation:

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

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

5 simulating multiple coin toss events

Suppose you need to simulate multiple coin toss events, where 0 represents the front and 1 for the opposite, and you can write code like this:

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

Or use a list build to make your code simpler:

From random import random
results = [Int (round (random ())) 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 floating-point number from 0 to 1, rounding the output returns 0 or 1. The Round () function returns a floating-point type of data, using int () to convert it to an integral type and add it to the list.

6 Remove the vowel letters from the sentence

Suppose you have a sentence,

Sentence = ' Your mother was a hamster '

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

vowels = ' aeiou '
non_list = [] for
l in sentence:
 if not 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-sentence if not L-in vowels])

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

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

vowels = ' aeiou '
nonvowels = '. Join (L for L-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 a list or generator. This syntax without square brackets uses a builder. This produces the same result (as in the list-generation), and the generator produces the corresponding entry when we traverse it, relative to wrapping all the items into a list before. 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 iterate through the files in the My_dir directory and append each file name to txt suffix in the files.

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

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

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

Or you can get a list of relative paths:

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

Thank you for the RASBT on Reddit.

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 CSV
data = [] for
x in CSV. Dictreader (Open (' file.csv ', ' RU ')):
 data.append (x)

You can use a list-generation to quickly implement:

Import CSV
data = [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 of 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 filename, and the second is the pattern. In this example, ' RU ' has two meanings. As always, ' r ' means opening a file in read mode. ' U ' indicates that we will accept universal line breaks-' n ', ' R ' and ' RN '.

Thank you for the BLACWIDONSFW on Reddit.

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.