## Cunning or orthodox Kung Fu? The most complete usage of Python derivation

Liu Zaoqi 2021-01-21 09:59:38
cunning orthodox kung fu complete

1 Pythonic - very Python

Write a piece of code to generate 1 To 100 A list of the squares of the numbers between , The answer is ：

`1,4,9,16...`

If you write it this way , You don't Pythonic 了 ：

```nums = []
for i in range(1,101):
nums.append(i*i)
print(nums)```

The correct way to write it is to use Python Derivation ：

`nums = [i*i for i in range(1,101)]`

## 2 A conditional derivation

Generate a list , contain 1 To 100 Between 3 The number of multiples of ：

`9,36,81...`

Code ：

`nums = [i*i for i in range(1,101) if i%3==0]`

## 3 Conditional expressions

Generate a list , If it is 3 Use the square as a multiple of , Otherwise, it's the number itself ：

`1,2,9,4,5,36...`

Code ：

`nums = [i*i if i%3==0 else i for i in range(1,101)]`

Combine the above 3 An example , Let's take a look at the deductive summary ：

1. Derivation from an enumerable data （ list , Tuples , aggregate , Dictionary, etc ） Deduce a list . You can also derive generators , A collection or dictionary .
2. The derivation can be added with derivation conditions , Only for the elements that meet the conditions
3. The elements to be derived are generated using expressions , It can be used if else Generate different elements
`[ expression if Expression conditions else Branch for i in Sequence if Derivation conditions ]`

## 4 Using functions

What if the derivation conditions or expressions are particularly complex ？ You can use functions .

Deduce all 1-100 All prime numbers between ：2,3,5,7...

```def is_prime(num):
if num == 1:
return False
for i in range(2,num):
if (num % i) == 0:
return False
else:
return True
p_nums = [i for i in range(1,100) if is_prime(i)]
print(p_nums)```

Put the derived conditions in the function , It can deal with complex conditions , We can also use the concise expression of derivation .

Empathy , If the process of generating derivation results is complex , You can also put logic into functions .

deduction 1900 To 2021 Between years, all the years , Mark leap years , Generate results ：

`1900, 1901, 1902, 1903, ' Leap 1904'`

Code ：

```def is_run(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True # A hundred years can be 400 Divided by leap years
else:
return False
else:
return True # Not for a hundred years 4 Divided by leap year
else:
return False
ryears = [f' Leap {y}' if is_run(y) else y for y in range(1900, 2021)]
print(ryears)```

## 5 Nested expressions - It is not recommended to use

from 2000 Year to 2021 year , Generate every month ：'2000 year :1 month ', '2000 year :2 month ', '2020 year :3 month ', ..., '2021 year :12 month '

`monthes = [f'{y} year :{m} month ' for y in range(2000, 2022) for m in range(1,13) ]`

There are two for loop , Be similar to ：

```monthes = []
for y in range(2000, 2022):
for m in range(1,13):
monthes.append(f'{y} year :{m} month ')```

Is the following particularly easy to understand ？ So derivation is not recommended for two-layer loops , ha-ha .

Then why do I have to talk about ？ You'll meet people who write that , It's necessary to know that it exists .

## 6 Derive a huge list - Don't do that ！

Deduce 1 To 100 The square of a number between 100 million , The code is as follows ：

`nums = [i*i for i in range(1,10000000000)]`

But this code is likely to jam your computer , Unless your computer is a supercomputer . Because it has to be done in memory 100 Billion calculations , And then save this 100 An digital .

## 7 Using the generator

In this case , We should use the derivation generator , It's easy to use ：

• Just change the square brackets to round brackets
```nums = (i*i for i in range(1,10000000000))
print(nums)
print(next(nums))
print(next(nums))
print(next(nums))```

Printed out is a generator ：

```<generator object <genexpr> at 0x7fa0b422feb0>
1
4
9```

This is a generator , It won't be generated all at once 100 An digital , Only a call next() When , It will generate a new one , Back to you . in other words , At the same time , Save only one number .

## 8 Derivation Dictionary

The way a dictionary is derived is very similar to the way a list is derived , It's just ：

1. Use braces
2. Use key-value pairs

Deduce a dictionary of numbers and squares of numbers , It turns out like this ：

`{1: 1, 2: 4, 3: 9, ..., 100: 10000}`

Code ：

```nums_dict = {n:n*n for n in range(1,101)}
print(nums_dict)```

In turn, , The square is ahead , The numbers are at the back ：

```nums_dict = {n*n:n for n in range(1,101)}
print(nums_dict)```

Sort the dictionaries below by score ：

`{' Uncle Mai ':59, ' Zhang San ':87, 'FGA':78, ' Stone stone ':100, ' Inexplicable ':90}`

Sorting result ：

`{' Stone stone ': 100, ' Inexplicable ': 90, ' Zhang San ': 87, 'FGA': 78, ' Uncle Mai ': 59}`

Code ：

```scores = {' Uncle Mai ':59, ' Zhang San ':87, 'FGA':78, ' Stone stone ':100, ' Inexplicable ':90}
sored_scores = {item[0]:item[1] for item in sorted(scores.items(), key=lambda item:item[1], reverse=True)}
print(sored_scores)```
1. First put the dictionary scores Into a tuple list ：scores.items()
2. use sorted Function to sort the list of tuples ：sorted(scores.items(), key=lambda item:item[1], reverse=True)
3. The sorting process uses lambda Specifies that the second column of the tuple is used to sort ：key=lambda item:item[1]. The default is the first column .
4. Specify reverse sort , That is, the ones with high scores are in the front ：reverse=True
5. Use the derivation , List the ordered tuples , Generate a new ordered Dictionary ：{item[0]:item[1] for item in ... }

## 9 Deducing sets Set

The way collections are derived is the same as lists , The difference lies in ：

1. Use braces , It's like deducing a dictionary , But it's a single element , Not key value pairs .
2. The collection automatically filters out duplicate elements .

The following list of names , Remove the spaces before and after, and then remove the duplicate names ：

`[ ' Uncle Mai ', ' Zhang San ', ' Uncle Mai ', 'FGA ', ' Zhang Xiaosan ', 'FGA', ' Stone stone ',' Inexplicable ',' Inexplicable ' ]`

The derivation results ：

`{' Stone stone ', 'FGA', ' Zhang Xiaosan ', ' Inexplicable ', ' Zhang San ', ' Uncle Mai '}`

Code ：

```names = [ ' Uncle Mai ', ' Zhang San ', ' Uncle Mai ', 'FGA ', ' Zhang Xiaosan ', 'FGA', ' Stone stone ',' Inexplicable ',' Inexplicable ' ]
new_names = {n.strip() for n in names}
print(new_names)```

-END-