List generation
List generation or list parsing
Format:
[expression for i in sequence ]
Topic 1
Generate a list with the square of 1-N [1 * * 2,2 * * 2,3 * * 2,4 * * 2,..., n * * 2]
General method:
li = [] for i in range(1,11): li.append(i**2) print(li)
List generation:
print([i ** 2 for i in range(1,11)])
The form of adding if judgment condition
Format:
[expression for i in sequence if...]
Topic 1
Generate a list of all even numbers between 1 and 10
General method:
li = [] for i in range(1,11): if i %2 == 0: li.append( i**2 ) print(li)
List generation:
print([i ** 2 for i in range(1,11) if i %2 == 0])
Topic two
Find all the even numbers between 1 and 10, and return a list (including the area of the circle with the even radius)
Expression of pi value:
import math a = math.pi print(a)
List generation:
import math a = math.pi print([math.pi * i * i for i in range(1,11) if i % 2 == 0])
Topic three
Find out all prime numbers between 1 and num
def isPrime(num): for i in range(2,num): if num % i == 0: # Not prime numbers. return False else: # Align with for, otherwise the loop is incomplete, and the non prime number will be taken out. return True print([i for i in range(2,101) if isPrime(i)])
Topic four
Given a string, the following code is expressed in list generation
s = '51 5000 10000' li = [] for item in s.split(): li.append(int(item)) print(li)
List generation:
s = '51 5000 10000' print([int(item) for item in s.split()])
Topic five
Find out the file ending with. Log in the log / var/log directory and print it out
To import a virtual command line:
import os print(os.listdir('/var/log'))
The list generation is implemented as follows:
import os print([filename for filename in os.listdir('/var/log') if filename.endswith('.log')])
List generated deformation
s1 = 'ABC'
s2='123'
List of required outputs: A1 A2 A3... C1 C2 C3
List generation:
s1 = 'ABC' s2 = '123' print([i + j for i in 'ABC' for j in '123'])
Given list li, output list is required [1,2,3,4,5,6,7,8,9]
General method:
li = [ [1,2,3], [4,5,6], [7,8,9] ] resultli = [] for i in li: for j in i: resultli.append(j) print(resultli)
List generation:
li = [ [1,2,3], [4,5,6], [7,8,9] ] print([j for i in li for j in i ])