Demonstrate the list generative usage in Python using code instances.

Source: Internet
Author: User

Demonstrate the list generative usage in Python using code instances.

1 sq list

If you want to create a list containing 1 to 10 square meters, you can do this:

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

 

This is a simple example, but you can use the list generator to create this list more concisely.

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

The simplest list generation method starts with square brackets. Square brackets start with an expression, followed by a for statement. The list generator always returns a list.

List of numbers in the division of 2 and 3

Generally, you may write as follows:

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

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

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

3. Locate the prime number

This usually requires several lines of code.

noprimes = []for i in range(2, 8): for j in range(i*2, 50, i):  noprimes.append(j)primes = []for x in range(2, 50): if x not in noprimes:  primes.append(x)

However, you can use two list generators to simplify the code.

noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]primes = [x for x in range(2, 50) if x not in noprimes]

The first line of code uses a multi-layer for loop in a list generator. The first cycle is an external loop, and the second is an internal loop. To locate the prime number, we first find a list of non-prime numbers. This non-Prime Number list is generated by finding a multiple of 2-7. Then we traverse the number cyclically and check whether each number is in the list of non-prime numbers.

Correction: As shoyer on reddit pointed out, it is more efficient to use a set to search for noprimes (attribute parameters in the code, Translator's note. Since noprimes should only contain unique values, and we frequently check whether a value exists, we should use a set. The syntax for using a set is similar to that for using a list, so we can use it like this:

noprimes = set(j for i in range(2, 8) for j in range(i*2, 50, i))primes = [x for x in range(2, 50) if x not in noprimes]

4. nested list Dimension Reduction

Suppose you have a list (the list contains a list) 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)

List generation:

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

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

5. Simulate multiple coin Throwing Events

Assume that you need to simulate multiple coin throwing events. 0 indicates the front and 1 indicates the opposite. You can write code like this:

from random import randomresults = []for x in range(10): results.append(int(round(random())))

Or use the list generator to make the code more concise:

from random import randomresults = [int(round(random())) for x in range(10)]

The range function is used for 10 times. Every time we round the output of random. Because the random () function returns a floating point number ranging from 0 to 1, the return value is 0 or 1 after rounding the output. The Round () function returns a floating point data, converts it to an integer using int (), and adds it to the list.

6. Remove the vowels from a sentence.

Suppose you have a sentence,

sentence = 'Your mother was a hamster'

And you want to remove all vowels. We can use several lines of code to 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 use the list generator to simplify it:

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

In this example, a list is generated to create a letter list. The letters in the letter list come from non-Vowels in sentence sentences. Then we pass the generated list to the join () function to convert it into a string.

Correction: As iamadogwhatisthis on reddit proposed, this example does not require list generation. It is better to use the generator (generator:

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

Note that square brackets are removed here. This is because the join function receives any data that can be iterated, including the list or generator. The syntax without square brackets uses the generator. This produces the same results (as the list generation formula). The generator generates corresponding entries only after we wrap all the entries into a list. This eliminates the need to save the entire list to the memory and is more efficient for processing large amounts of data.

7. Get the file name list in the directory

The following code will traverse the files under the my_dir directory and append each file name suffixed with txt in files.

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

This can also simplify the code by using list generation:

import osfiles = [f for f in os.listdir('./my_dir') if f.endswith('.txt')]

Alternatively, you can obtain 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 rasbt on reddit.

8. Read the csv file as a dictionary list.

We often need to read and process csv file data. The most useful way to process csv data is to convert it into a dictionary list.

import csvdata = []for x in csv.DictReader(open('file.csv', 'rU')): data.append(x)

You can use the list generator to quickly implement:

import csvdata = [ x for x in csv.DictReader(open('file.csv', 'rU'))]

The DictReader class automatically uses the first line of the csv file as the dictionary key attribute name. The DictReader class returns an object that will traverse all rows in the csv file. This file object is generated by the open () function. We provide two parameters-the first is the csv file name and the second is the mode. In this example, 'ru 'has two meanings. As usual, 'R' indicates opening the file in Read mode. 'U' indicates that we will accept the common line breaks-'n', 'R', and 'rn '.

Thanks to 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.