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-

This article is from WeChat official account. - Get up early Python(zaoqi-python)

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2021-01-09

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Liu Zaoqi]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/01/20210121095345055n.html

  1. Python批量 png转ico
  2. 使用line_profiler对python代码性能进行评估优化
  3. 使用line_profiler对python代码性能进行评估优化
  4. Getting started with Python 3 flash in win environment
  5. Common ways to write configuration files in Python
  6. Python会在2021年死去吗? Python 3.9最终版本的回顾
  7. Python batch PNG to ICO
  8. Using line_ Profiler evaluates and optimizes the performance of Python code
  9. Using line_ Profiler evaluates and optimizes the performance of Python code
  10. Will Python die in 2021? A review of the final version of Python 3.9
  11. Python3 SMTP send mail
  12. Understanding closures in Python: getting started with closures
  13. Python日志实践
  14. Python logging practice
  15. [python opencv 计算机视觉零基础到实战] 十、图片效果毛玻璃
  16. [python opencv 计算机视觉零基础到实战] 九、模糊
  17. 10. Picture effect ground glass
  18. [Python opencv computer vision zero basis to actual combat] 9. Fuzzy
  19. 使用line_profiler對python程式碼效能進行評估優化
  20. Using line_ Profiler to evaluate and optimize the performance of Python code
  21. LeetCode | 0508. 出现次数最多的子树元素和【Python】
  22. Leetcode | 0508
  23. LeetCode | 0530. 二叉搜索树的最小绝对差【Python】
  24. LeetCode | 0515. 在每个树行中找最大值【Python】
  25. Leetcode | 0530. Minimum absolute difference of binary search tree [Python]
  26. Leetcode | 0515. Find the maximum value in each tree row [Python]
  27. 我来记笔记啦-搭建python虚拟环境
  28. Let me take notes - building a python virtual environment
  29. LeetCode | 0513. 找树左下角的值【Python】
  30. Leetcode | 0513. Find the value in the lower left corner of the tree [Python]
  31. Python OpenCV 泛洪填充,取经之旅第 21 天
  32. Python opencv flood fill, day 21
  33. Python爬虫自学系列(二)
  34. Python crawler self study series (2)
  35. 【python】身份证号码有效性检验
  36. [Python] validity test of ID number
  37. Python ORM - pymysql&sqlalchemy
  38. Python ORM - pymysql&sqlalchemy
  39. centos7 安装python3.8
  40. centos7 安装python3.8
  41. Centos7 installing Python 3.8
  42. Centos7 installing Python 3.8
  43. Django——图书管理系统(六)
  44. Django——图书管理系统(五)
  45. Django -- library management system (6)
  46. Django -- library management system (5)
  47. python批量插入数据小脚本
  48. Python batch insert data script
  49. ZoomEye-python 使用指南
  50. Zoomeye Python User's Guide
  51. 用Python写代码,一分钟搞定一天工作量,同事直呼:好家伙 - 知乎
  52. Using Python to write code, one minute to complete a day's workload, colleagues call: good guy - Zhihu
  53. Python 上的可视化库——PyG2Plot
  54. Pyg2plot: a visualization library on Python
  55. Python 上的可视化库——PyG2Plot
  56. Python实用代码-无限级分类树状结构生成算法
  57. Pyg2plot: a visualization library on Python
  58. Python utility code - infinite classification tree structure generation algorithm
  59. 奇技淫巧,还是正统功夫?Python推导式最全用法
  60. Pandas 的这个知识点,估计 80% 的人都得挂!