Various leg play

1. Derivative routine

Earlier we've learned about the simplest list comprehensions and generator expressions. But in addition, there are actually dictionary comprehensions, set comprehensions, and so on.

variable = [out_exp_res for out_exp in input_list if out_exp == 2]
    out_exp_res: The list generates element expressions, which can be used to return functions.
    for out_exp in input_list: Iterate over the input_list or out_exp_res expressions.
    if out_exp == 2: Filter which values ​​are ok based on the condition.

2. List Comprehension

Example 1:: All numbers within 30 that are divisible by 3

listt = [i for i in range(30) if i % 3 is 0]
print(listt)
View Code

Example 2: The square of all numbers within 30 that are divisible by 3

def squared(x):
    return x*x

listt = [squared(i) for i in range(30) if i % 3 is 0]
print(listt)
View Code

Example 3: Find all names in nested lists whose names contain two 'e's

names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
        ['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]

n = [name for lst in names for name in lst if name.count('e')>=2]
print(n)
View Code

3. Dictionary comprehension

Example 1: Swap the key and value of a dictionary

tupt = {'a':10,'b':34}

tupt_frequency = {tupt[k]: k for k in tupt}
print(tupt_frequency)


#decomposition instruction # for k in tupt: 
# 
print      (tupt[k]) #result 10 34

#k for k in tupt  结果 a b

#所以{tupt[k]: k for k in tupt} 是 10:a 34:b
View Code

Example 2: Combine the value values ​​corresponding to upper and lower case, and unify k into lower case

tupt = {'a':10,'b':34,'A':7,'D':9}
tupt_frequency ={k.lower():tupt.get(k.lower(),0) + tupt.get(k.upper(),0) for k in tupt.keys()}

print(tupt_frequency)
View Code

4. Set derivation

Example 1: Calculate the square of each value in the list, with its own deduplication function

print(squared)
View Code

 

practise

listt = ["dasd","sdas","sd","b"]
listt_fre = {i.upper() for i in listt if len(i)<3}
print(listt_fre)
Filter out a list of strings with length less than 3 and convert the rest to uppercase

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324923415&siteId=291194637