├── .gitignore
├── .nojekyll
├── 404.html
├── CNAME
├── Dockerfile
├── LICENSE
├── NAV.md
├── README.md
├── SUMMARY.md
├── asset
├── back-to-top.css
├── back-to-top.js
├── dark-mode.css
├── dark-mode.js
├── docsify-apachecn-footer.js
├── docsify-baidu-push.js
├── docsify-baidu-stat.js
├── docsify-clicker.js
├── docsify-cnzz.js
├── docsify-copy-code.min.js
├── docsify-quick-page.css
├── docsify-quick-page.js
├── docsify-sidebar-collapse.min.js
├── docsify.min.js
├── edit.css
├── edit.js
├── edit.svg
├── left.svg
├── moon.svg
├── prism-darcula.css
├── prism-python.min.js
├── right.svg
├── search.min.js
├── share.css
├── share.js
├── share.svg
├── sidebar.min.css
├── style.css
├── sun.svg
├── up.svg
└── vue.css
├── docs
├── 10.md
├── 11.md
├── 12.md
├── 13.md
├── 14.md
├── 15.md
├── 16.md
├── 17.md
├── 18.md
├── 19.md
├── 2.md
├── 20.md
├── 21.md
├── 22.md
├── 23.md
├── 24.md
├── 25.md
├── 26.md
├── 27.md
├── 28.md
├── 29.md
├── 3.md
├── 30.md
├── 31.md
├── 32.md
├── 33.md
├── 34.md
├── 35.md
├── 36.md
├── 37.md
├── 38.md
├── 39.md
├── 4.md
├── 40.md
├── 41.md
├── 42.md
├── 43.md
├── 44.md
├── 45.md
├── 46.md
├── 47.md
├── 48.md
├── 49.md
├── 5.md
├── 50.md
├── 51.md
├── 52.md
├── 53.md
├── 54.md
├── 55.md
├── 56.md
├── 57.md
├── 58.md
├── 59.md
├── 6.md
├── 60.md
├── 61.md
├── 62.md
├── 63.md
├── 64.md
├── 65.md
├── 66.md
├── 67.md
├── 68.md
├── 7.md
├── 8.md
├── 9.md
└── img
│ ├── 08b661eaec8ff40dbd5e2fbc5e7bb843.png
│ ├── 1465df1cc7b49f4ef431f26f7e1627ab.png
│ ├── 1bd07b9ee86ea977adf3c113fe0e0939.png
│ ├── 6113451b01106e8adff5df5b50e8d069.png
│ ├── 72eeb7f2bbb92ad38bfff7f133d3c3cc.png
│ ├── 96a007840d513479e414cd40e5b67e2c.png
│ ├── a221810ac323791d4ac671449aa078e1.png
│ ├── fe7cf26a723283da03ef589149ee7c3c.png
│ └── ff8e1e812772d3d072395aa647df7499.png
├── index.html
└── update.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 |
49 | # Translations
50 | *.mo
51 | *.pot
52 |
53 | # Django stuff:
54 | *.log
55 | local_settings.py
56 |
57 | # Flask stuff:
58 | instance/
59 | .webassets-cache
60 |
61 | # Scrapy stuff:
62 | .scrapy
63 |
64 | # Sphinx documentation
65 | docs/_build/
66 |
67 | # PyBuilder
68 | target/
69 |
70 | # Jupyter Notebook
71 | .ipynb_checkpoints
72 |
73 | # pyenv
74 | .python-version
75 |
76 | # celery beat schedule file
77 | celerybeat-schedule
78 |
79 | # SageMath parsed files
80 | *.sage.py
81 |
82 | # dotenv
83 | .env
84 |
85 | # virtualenv
86 | .venv
87 | venv/
88 | ENV/
89 |
90 | # Spyder project settings
91 | .spyderproject
92 | .spyproject
93 |
94 | # Rope project settings
95 | .ropeproject
96 |
97 | # mkdocs documentation
98 | /site
99 |
100 | # mypy
101 | .mypy_cache/
102 | .DS_Store
103 |
104 | # gitbook
105 | _book
106 |
107 | # node.js
108 | node_modules
109 |
110 | # windows
111 | Thumbs.db
112 |
113 | # word
114 | ~$*.docx
115 | ~$*.doc
116 |
--------------------------------------------------------------------------------
/.nojekyll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apachecn/pythonguru-zh/50a9e308f6b667220a64ca5f98b666cf345c1586/.nojekyll
--------------------------------------------------------------------------------
/404.html:
--------------------------------------------------------------------------------
1 | ---
2 | permalink: /404.html
3 | ---
4 |
5 |
--------------------------------------------------------------------------------
/CNAME:
--------------------------------------------------------------------------------
1 | pygr.apachecn.org
2 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM httpd:2.4
2 | COPY ./ /usr/local/apache2/htdocs/
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PythonGuru 中文系列教程
2 |
3 | > 原文:[PythonGuru](https://thepythonguru.com/)
4 | >
5 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
6 | >
7 | > 问:如何生成随机数?答:让新手退出 vim。
8 |
9 | * [在线阅读](http://pygr.apachecn.org/)
10 | * [在线阅读(Gitee)](https://apachecn.gitee.io/pythonguru-zh/)
11 | * [ApacheCN 学习资源](http://docs.apachecn.org/)
12 |
13 | ## 贡献指南
14 |
15 | 为了不断改进翻译质量,我们特此启动了【翻译、校对、笔记整理活动】,开设了多个校对项目。贡献者校对一章之后可以领取千字2\~4元的奖励。进行中的校对活动请见[活动列表](https://home.apachecn.org/#/docs/activity/docs-activity)。更多详情请联系飞龙(Q562826179,V:wizardforcel)。
16 |
17 | ## 联系方式
18 |
19 | ### 负责人
20 |
21 | * [飞龙](https://github.com/wizardforcel): 562826179
22 |
23 | ### 其他
24 |
25 | * 在我们的 [apachecn/pythonguru-zh](https://github.com/apachecn/pythonguru-zh) github 上提 issue.
26 | * 发邮件到 Email: `apachecn@163.com`.
27 | * 在我们的 [组织学习交流群](http://www.apachecn.org/organization/348.html) 中联系群主/管理员即可.
28 |
29 | ## 下载
30 |
31 | ### Docker
32 |
33 | ```
34 | docker pull apachecn0/pythonguru-zh
35 | docker run -tid -p :80 apachecn0/pythonguru-zh
36 | # 访问 http://localhost:{port} 查看文档
37 | ```
38 |
39 | ### PYPI
40 |
41 | ```
42 | pip install pythonguru-zh
43 | pythonguru-zh
44 | # 访问 http://localhost:{port} 查看文档
45 | ```
46 |
47 | ### NPM
48 |
49 | ```
50 | npm install -g pythonguru-zh
51 | pythonguru-zh
52 | # 访问 http://localhost:{port} 查看文档
53 | ```
54 |
55 | ## 赞助我们
56 |
57 | 
58 |
--------------------------------------------------------------------------------
/SUMMARY.md:
--------------------------------------------------------------------------------
1 | + [初级 Python](docs/2.md)
2 | + [python 入门](docs/3.md)
3 | + [安装 Python3](docs/4.md)
4 | + [运行 python 程序](docs/5.md)
5 | + [数据类型和变量](docs/6.md)
6 | + [Python 数字](docs/7.md)
7 | + [Python 字符串](docs/8.md)
8 | + [Python 列表](docs/9.md)
9 | + [Python 字典](docs/10.md)
10 | + [Python 元组](docs/11.md)
11 | + [数据类型转换](docs/12.md)
12 | + [Python 控制语句](docs/13.md)
13 | + [Python 函数](docs/14.md)
14 | + [Python 循环](docs/15.md)
15 | + [Python 数学函数](docs/16.md)
16 | + [Python 生成随机数](docs/17.md)
17 | + [Python 文件处理](docs/18.md)
18 | + [Python 对象和类](docs/19.md)
19 | + [Python 运算符重载](docs/20.md)
20 | + [Python 继承与多态](docs/21.md)
21 | + [Python 异常处理](docs/22.md)
22 | + [Python 模块](docs/23.md)
23 | + [高级 Python](docs/24.md)
24 | + [Python `*args`和`**kwargs`](docs/25.md)
25 | + [Python 生成器](docs/26.md)
26 | + [Python 正则表达式](docs/27.md)
27 | + [使用 PIP 在 python 中安装包](docs/28.md)
28 | + [Python `virtualenv`指南](docs/29.md)
29 | + [Python 递归函数](docs/30.md)
30 | + [`__name__ == "__main__"`是什么?](docs/31.md)
31 | + [Python Lambda 函数](docs/32.md)
32 | + [Python 字符串格式化](docs/33.md)
33 | + [Python 内置函数和方法](docs/34.md)
34 | + [Python `abs()`函数](docs/35.md)
35 | + [Python `bin()`函数](docs/36.md)
36 | + [Python `id()`函数](docs/37.md)
37 | + [Python `map()`函数](docs/38.md)
38 | + [Python `zip()`函数](docs/39.md)
39 | + [Python `filter()`函数](docs/40.md)
40 | + [Python `reduce()`函数](docs/41.md)
41 | + [Python `sorted()`函数](docs/42.md)
42 | + [Python `enumerate()`函数](docs/43.md)
43 | + [Python `reversed()`函数](docs/44.md)
44 | + [Python `range()`函数](docs/45.md)
45 | + [Python `sum()`函数](docs/46.md)
46 | + [Python `max()`函数](docs/47.md)
47 | + [Python `min()`函数](docs/48.md)
48 | + [Python `eval()`函数](docs/49.md)
49 | + [Python `len()`函数](docs/50.md)
50 | + [Python `ord()`函数](docs/51.md)
51 | + [Python `chr()`函数](docs/52.md)
52 | + [Python `any()`函数](docs/53.md)
53 | + [Python `all()`函数](docs/54.md)
54 | + [Python `globals()`函数](docs/55.md)
55 | + [Python `locals()`函数](docs/56.md)
56 | + [数据库访问](docs/57.md)
57 | + [安装 Python MySQLdb](docs/58.md)
58 | + [连接到数据库](docs/59.md)
59 | + [MySQLdb 获取结果](docs/60.md)
60 | + [插入行](docs/61.md)
61 | + [处理错误](docs/62.md)
62 | + [使用`fetchone()`和`fetchmany()`获取记录](docs/63.md)
63 | + [常见做法](docs/64.md)
64 | + [Python:如何读取和写入文件](docs/65.md)
65 | + [Python:如何读取和写入 CSV 文件](docs/66.md)
66 | + [用 Python 读写 JSON](docs/67.md)
67 | + [用 Python 转储对象](docs/68.md)
68 |
--------------------------------------------------------------------------------
/asset/back-to-top.css:
--------------------------------------------------------------------------------
1 | #scroll-btn {
2 | position: fixed;
3 | right: 15px;
4 | bottom: 10px;
5 | width: 35px;
6 | height: 35px;
7 | background-repeat: no-repeat;
8 | background-size: cover;
9 | cursor: pointer;
10 | -webkit-user-select: none;
11 | -moz-user-select: none;
12 | -ms-user-select: none;
13 | user-select: none;
14 | background-image: url(up.svg);
15 | background-position-y: -1px;
16 | display: none;
17 | border: 2px solid;
18 | border-radius: 4px;
19 | }
--------------------------------------------------------------------------------
/asset/back-to-top.js:
--------------------------------------------------------------------------------
1 | document.addEventListener('DOMContentLoaded', function() {
2 | var scrollBtn = document.createElement('div')
3 | scrollBtn.id = 'scroll-btn'
4 | document.body.append(scrollBtn)
5 |
6 | window.addEventListener('scroll', function() {
7 | var offset = window.document.documentElement.scrollTop;
8 | scrollBtn.style.display = offset >= 500 ? "block" : "none";
9 | })
10 | scrollBtn.addEventListener('click', function(e) {
11 | e.stopPropagation();
12 | var step = window.scrollY / 15;
13 | var hdl = setInterval(function() {
14 | window.scrollTo(0, window.scrollY - step);
15 | if(window.scrollY <= 0) {
16 | clearInterval(hdl)
17 | }
18 | }, 15)
19 | })
20 | })
--------------------------------------------------------------------------------
/asset/dark-mode.css:
--------------------------------------------------------------------------------
1 | #dark-mode-btn {
2 | position: fixed;
3 | right: 15px;
4 | top: 100px;
5 | width: 35px;
6 | height: 35px;
7 | background-repeat: no-repeat;
8 | background-size: cover;
9 | cursor: pointer;
10 | -webkit-user-select: none;
11 | -moz-user-select: none;
12 | -ms-user-select: none;
13 | user-select: none;
14 | transition: background-image .15s ease-in-out .15s;
15 | }
16 |
17 | .dark-logo {
18 | background-image: url('sun.svg');
19 | }
20 |
21 | .light-logo {
22 | background-image: url('moon.svg');
23 | }
--------------------------------------------------------------------------------
/asset/dark-mode.js:
--------------------------------------------------------------------------------
1 | document.addEventListener('DOMContentLoaded', function() {
2 | var style = document.querySelector('#invert')
3 | if (style == null) {
4 | style = document.createElement('style')
5 | style.id = 'invert'
6 | document.head.append(style)
7 | }
8 | var btn = document.querySelector('#dark-mode-btn')
9 | if (btn == null) {
10 | btn = document.createElement('div')
11 | btn.id = 'dark-mode-btn'
12 | btn.classList.add('light-logo')
13 | document.body.append(btn)
14 | }
15 |
16 | var enableDarkMode = function() {
17 | style.innerText = 'html,img,pre,#dark-mode-btn{filter:invert(100%)}'
18 | btn.classList.remove('light-logo')
19 | btn.classList.add('dark-logo')
20 | localStorage.darkLight = 'dark'
21 |
22 | }
23 | var disableDarkMode = function() {
24 | style.innerText = ''
25 | btn.classList.remove('dark-logo')
26 | btn.classList.add('light-logo')
27 | localStorage.darkLight = 'light'
28 | }
29 |
30 | btn.addEventListener('click', function(){
31 | var currMode = localStorage.darkLight || 'light'
32 | if (currMode == 'light')
33 | enableDarkMode()
34 | else
35 | disableDarkMode()
36 | })
37 |
38 | if (localStorage.darkLight == 'dark')
39 | enableDarkMode()
40 |
41 | })
42 |
43 |
--------------------------------------------------------------------------------
/asset/docsify-apachecn-footer.js:
--------------------------------------------------------------------------------
1 | (function(){
2 | var cnzzId = window.$docsify.cnzzId
3 | var unRepo = window.$docsify.repo || ''
4 | var [un, repo] = unRepo.split('/')
5 | var footer = `
6 |
7 |
22 | `
23 | var plugin = function(hook) {
24 | hook.afterEach(function(html) {
25 | return html + footer
26 | })
27 | hook.doneEach(function() {
28 | (adsbygoogle = window.adsbygoogle || []).push({})
29 | })
30 | }
31 | var plugins = window.$docsify.plugins || []
32 | plugins.push(plugin)
33 | window.$docsify.plugins = plugins
34 | })()
--------------------------------------------------------------------------------
/asset/docsify-baidu-push.js:
--------------------------------------------------------------------------------
1 | (function(){
2 | var plugin = function(hook) {
3 | hook.doneEach(function() {
4 | new Image().src =
5 | '//api.share.baidu.com/s.gif?r=' +
6 | encodeURIComponent(document.referrer) +
7 | "&l=" + encodeURIComponent(location.href)
8 | })
9 | }
10 | var plugins = window.$docsify.plugins || []
11 | plugins.push(plugin)
12 | window.$docsify.plugins = plugins
13 | })()
--------------------------------------------------------------------------------
/asset/docsify-baidu-stat.js:
--------------------------------------------------------------------------------
1 | (function(){
2 | var plugin = function(hook) {
3 | hook.doneEach(function() {
4 | window._hmt = window._hmt || []
5 | var hm = document.createElement("script")
6 | hm.src = "https://hm.baidu.com/hm.js?" + window.$docsify.bdStatId
7 | document.querySelector("article").appendChild(hm)
8 | })
9 | }
10 | var plugins = window.$docsify.plugins || []
11 | plugins.push(plugin)
12 | window.$docsify.plugins = plugins
13 | })()
--------------------------------------------------------------------------------
/asset/docsify-cnzz.js:
--------------------------------------------------------------------------------
1 | (function(){
2 | var plugin = function(hook) {
3 | hook.doneEach(function() {
4 | var sc = document.createElement('script')
5 | sc.src = 'https://s5.cnzz.com/z_stat.php?id=' +
6 | window.$docsify.cnzzId + '&online=1&show=line'
7 | document.querySelector('article').appendChild(sc)
8 | })
9 | }
10 | var plugins = window.$docsify.plugins || []
11 | plugins.push(plugin)
12 | window.$docsify.plugins = plugins
13 | })()
--------------------------------------------------------------------------------
/asset/docsify-copy-code.min.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * docsify-copy-code
3 | * v2.1.0
4 | * https://github.com/jperasmus/docsify-copy-code
5 | * (c) 2017-2019 JP Erasmus
6 | * MIT license
7 | */
8 | !function(){"use strict";function r(o){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}!function(o,e){void 0===e&&(e={});var t=e.insertAt;if(o&&"undefined"!=typeof document){var n=document.head||document.getElementsByTagName("head")[0],c=document.createElement("style");c.type="text/css","top"===t&&n.firstChild?n.insertBefore(c,n.firstChild):n.appendChild(c),c.styleSheet?c.styleSheet.cssText=o:c.appendChild(document.createTextNode(o))}}(".docsify-copy-code-button,.docsify-copy-code-button span{cursor:pointer;transition:all .25s ease}.docsify-copy-code-button{position:absolute;z-index:1;top:0;right:0;overflow:visible;padding:.65em .8em;border:0;border-radius:0;outline:0;font-size:1em;background:grey;background:var(--theme-color,grey);color:#fff;opacity:0}.docsify-copy-code-button span{border-radius:3px;background:inherit;pointer-events:none}.docsify-copy-code-button .error,.docsify-copy-code-button .success{position:absolute;z-index:-100;top:50%;left:0;padding:.5em .65em;font-size:.825em;opacity:0;-webkit-transform:translateY(-50%);transform:translateY(-50%)}.docsify-copy-code-button.error .error,.docsify-copy-code-button.success .success{opacity:1;-webkit-transform:translate(-115%,-50%);transform:translate(-115%,-50%)}.docsify-copy-code-button:focus,pre:hover .docsify-copy-code-button{opacity:1}"),document.querySelector('link[href*="docsify-copy-code"]')&&console.warn("[Deprecation] Link to external docsify-copy-code stylesheet is no longer necessary."),window.DocsifyCopyCodePlugin={init:function(){return function(o,e){o.ready(function(){console.warn("[Deprecation] Manually initializing docsify-copy-code using window.DocsifyCopyCodePlugin.init() is no longer necessary.")})}}},window.$docsify=window.$docsify||{},window.$docsify.plugins=[function(o,s){o.doneEach(function(){var o=Array.apply(null,document.querySelectorAll("pre[data-lang]")),c={buttonText:"Copy to clipboard",errorText:"Error",successText:"Copied"};s.config.copyCode&&Object.keys(c).forEach(function(t){var n=s.config.copyCode[t];"string"==typeof n?c[t]=n:"object"===r(n)&&Object.keys(n).some(function(o){var e=-1',''.concat(c.buttonText,""),''.concat(c.errorText,""),''.concat(c.successText,""),""].join("");o.forEach(function(o){o.insertAdjacentHTML("beforeend",e)})}),o.mounted(function(){document.querySelector(".content").addEventListener("click",function(o){if(o.target.classList.contains("docsify-copy-code-button")){var e="BUTTON"===o.target.tagName?o.target:o.target.parentNode,t=document.createRange(),n=e.parentNode.querySelector("code"),c=window.getSelection();t.selectNode(n),c.removeAllRanges(),c.addRange(t);try{document.execCommand("copy")&&(e.classList.add("success"),setTimeout(function(){e.classList.remove("success")},1e3))}catch(o){console.error("docsify-copy-code: ".concat(o)),e.classList.add("error"),setTimeout(function(){e.classList.remove("error")},1e3)}"function"==typeof(c=window.getSelection()).removeRange?c.removeRange(t):"function"==typeof c.removeAllRanges&&c.removeAllRanges()}})})}].concat(window.$docsify.plugins||[])}();
9 | //# sourceMappingURL=docsify-copy-code.min.js.map
10 |
--------------------------------------------------------------------------------
/asset/docsify-quick-page.css:
--------------------------------------------------------------------------------
1 | #prev-page-button {
2 | position:fixed;
3 | top:140px;
4 | width: 35px;
5 | height: 35px;
6 | right: 15px;
7 | background-color: transparent;
8 | background-image: url(left.svg);
9 | background-repeat: no-repeat;
10 | background-size: cover;
11 | border:0;
12 | -webkit-user-select: none;
13 | -moz-user-select: none;
14 | -ms-user-select: none;
15 | user-select: none;
16 | outline:none;
17 | cursor: pointer;
18 | }
19 |
20 | #next-page-button {
21 | position:fixed;
22 | top:180px;
23 | width:35px;
24 | height:35px;
25 | right:15px;
26 | background-color: transparent;
27 | background-image: url(right.svg);
28 | background-repeat: no-repeat;
29 | background-size: cover;
30 | border:0;
31 | -webkit-user-select: none;
32 | -moz-user-select: none;
33 | -ms-user-select: none;
34 | user-select: none;
35 | outline:none;
36 | cursor: pointer;
37 | }
--------------------------------------------------------------------------------
/asset/docsify-quick-page.js:
--------------------------------------------------------------------------------
1 | document.addEventListener('DOMContentLoaded', function() {
2 | var prevBtn = document.createElement("div")
3 | prevBtn.id = "prev-page-button"
4 | document.body.appendChild(prevBtn)
5 | var nextBtn = document.createElement("div");
6 | nextBtn.id = "next-page-button"
7 | document.body.appendChild(nextBtn)
8 |
9 | var links = null
10 | var linkMap = null
11 | var getCurIdx = function() {
12 | if (!links) {
13 | links = Array
14 | .from(document.querySelectorAll(".sidebar-nav a"))
15 | .map(x => x.href)
16 | linkMap = {}
17 | links.forEach((x, i) => linkMap[x] = i)
18 | }
19 |
20 | var elem = document.querySelector(".active a")
21 | var curIdx = elem? linkMap[elem.href]: -1
22 | return curIdx
23 | }
24 |
25 | prevBtn.addEventListener('click', function () {
26 | if (!document.body.classList.contains('ready'))
27 | return
28 | var curIdx = getCurIdx()
29 | location.href = curIdx == -1?
30 | links[0]:
31 | links[(curIdx - 1 + links.length) % links.length]
32 | document.body.scrollIntoView()
33 | }, false)
34 |
35 | nextBtn.addEventListener('click', function () {
36 | if (!document.body.classList.contains('ready'))
37 | return
38 | var curIdx = getCurIdx()
39 | location.href = links[(curIdx + 1) % links.length]
40 | document.body.scrollIntoView()
41 | }, false)
42 | })
--------------------------------------------------------------------------------
/asset/docsify-sidebar-collapse.min.js:
--------------------------------------------------------------------------------
1 | !function(e){("object"!=typeof exports||"undefined"==typeof module)&&"function"==typeof define&&define.amd?define(e):e()}(function(){"use strict";function e(e,n){var t,a=(n=void 0===n?{}:n).insertAt;e&&"undefined"!=typeof document&&(t=document.head||document.getElementsByTagName("head")[0],(n=document.createElement("style")).type="text/css","top"===a&&t.firstChild?t.insertBefore(n,t.firstChild):t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e)))}var t;function a(e){e&&null!=t&&(e=e.getBoundingClientRect().top,document.querySelector(".sidebar").scrollBy(0,e-t))}function n(){requestAnimationFrame(function(){var e=document.querySelector(".app-sub-sidebar > .active");if(e)for(e.parentNode.parentNode.querySelectorAll(".app-sub-sidebar").forEach(function(e){return e.classList.remove("open")});e.parentNode.classList.contains("app-sub-sidebar")&&!e.parentNode.classList.contains("open");)e.parentNode.classList.add("open"),e=e.parentNode})}function o(e){t=e.target.getBoundingClientRect().top;var n=d(e.target,"LI",2);n&&(n.classList.contains("open")?(n.classList.remove("open"),setTimeout(function(){n.classList.add("collapse")},0)):(function(e){if(e)for(e.classList.remove("open","active");e&&"sidebar-nav"!==e.className&&e.parentNode;)"LI"!==e.parentNode.tagName&&"app-sub-sidebar"!==e.parentNode.className||e.parentNode.classList.remove("open"),e=e.parentNode}(s()),i(n),setTimeout(function(){n.classList.remove("collapse")},0)),a(n))}function s(){var e=document.querySelector(".sidebar-nav .active");return e||(e=d(document.querySelector('.sidebar-nav a[href="'.concat(decodeURIComponent(location.hash).replace(/ /gi,"%20"),'"]')),"LI",2))&&e.classList.add("active"),e}function i(e){if(e)for(e.classList.add("open","active");e&&"sidebar-nav"!==e.className&&e.parentNode;)"LI"!==e.parentNode.tagName&&"app-sub-sidebar"!==e.parentNode.className||e.parentNode.classList.add("open"),e=e.parentNode}function d(e,n,t){if(e&&e.tagName===n)return e;for(var a=0;e;){if(t<++a)return;if(e.parentNode.tagName===n)return e.parentNode;e=e.parentNode}}e(".sidebar-nav > ul > li ul {\n display: none;\n}\n\n.app-sub-sidebar {\n display: none;\n}\n\n.app-sub-sidebar.open {\n display: block;\n}\n\n.sidebar-nav .open > ul:not(.app-sub-sidebar),\n.sidebar-nav .active:not(.collapse) > ul {\n display: block;\n}\n\n/* 抖动 */\n.sidebar-nav li.open:not(.collapse) > ul {\n display: block;\n}\n\n.active + ul.app-sub-sidebar {\n display: block;\n}\n"),document.addEventListener("scroll",n);e("@media screen and (max-width: 768px) {\n /* 移动端适配 */\n .markdown-section {\n max-width: none;\n padding: 16px;\n }\n /* 改变原来按钮热区大小 */\n .sidebar-toggle {\n padding: 0 0 10px 10px;\n }\n /* my pin */\n .sidebar-pin {\n appearance: none;\n outline: none;\n position: fixed;\n bottom: 0;\n border: none;\n width: 40px;\n height: 40px;\n background: transparent;\n }\n}\n");var r,c="DOCSIFY_SIDEBAR_PIN_FLAG";function l(){var e="true"===(e=localStorage.getItem(c));localStorage.setItem(c,!e),e?(document.querySelector(".sidebar").style.transform="translateX(0)",document.querySelector(".content").style.transform="translateX(0)"):(document.querySelector(".sidebar").style.transform="translateX(300px)",document.querySelector(".content").style.transform="translateX(300px)")}768 ul"),1),a(t),n(e)}),e.ready(function(){document.querySelector(".sidebar-nav").addEventListener("click",o)})})});
--------------------------------------------------------------------------------
/asset/edit.css:
--------------------------------------------------------------------------------
1 | #edit-btn {
2 | position: fixed;
3 | right: 15px;
4 | top: 260px;
5 | width: 35px;
6 | height: 35px;
7 | background-repeat: no-repeat;
8 | background-size: cover;
9 | cursor: pointer;
10 | -webkit-user-select: none;
11 | -moz-user-select: none;
12 | -ms-user-select: none;
13 | user-select: none;
14 | background-image: url(edit.svg);
15 | }
--------------------------------------------------------------------------------
/asset/edit.js:
--------------------------------------------------------------------------------
1 | document.addEventListener('DOMContentLoaded', function() {
2 | var editBtn = document.createElement('div')
3 | editBtn.id = 'edit-btn'
4 | document.body.append(editBtn)
5 |
6 | var repo = window.$docsify.repo
7 | editBtn.addEventListener('click', function() {
8 | if (!repo) return
9 | if (!/https?:\/\//.exec(repo))
10 | repo = 'https://github.com/' + repo
11 | var url = repo + '/tree/master' +
12 | location.hash.slice(1) + '.md'
13 | window.open(url)
14 | })
15 | })
--------------------------------------------------------------------------------
/asset/edit.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/asset/left.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/asset/moon.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/asset/prism-darcula.css:
--------------------------------------------------------------------------------
1 | /**
2 | * Darcula theme
3 | *
4 | * Adapted from a theme based on:
5 | * IntelliJ Darcula Theme (https://github.com/bulenkov/Darcula)
6 | *
7 | * @author Alexandre Paradis
8 | * @version 1.0
9 | */
10 |
11 | code[class*="lang-"],
12 | pre[data-lang] {
13 | color: #a9b7c6 !important;
14 | background-color: #2b2b2b !important;
15 | font-family: Consolas, Monaco, 'Andale Mono', monospace;
16 | direction: ltr;
17 | text-align: left;
18 | white-space: pre;
19 | word-spacing: normal;
20 | word-break: normal;
21 | line-height: 1.5;
22 |
23 | -moz-tab-size: 4;
24 | -o-tab-size: 4;
25 | tab-size: 4;
26 |
27 | -webkit-hyphens: none;
28 | -moz-hyphens: none;
29 | -ms-hyphens: none;
30 | hyphens: none;
31 | }
32 |
33 | pre[data-lang]::-moz-selection, pre[data-lang] ::-moz-selection,
34 | code[class*="lang-"]::-moz-selection, code[class*="lang-"] ::-moz-selection {
35 | color: inherit;
36 | background: rgba(33, 66, 131, .85);
37 | }
38 |
39 | pre[data-lang]::selection, pre[data-lang] ::selection,
40 | code[class*="lang-"]::selection, code[class*="lang-"] ::selection {
41 | color: inherit;
42 | background: rgba(33, 66, 131, .85);
43 | }
44 |
45 | /* Code blocks */
46 | pre[data-lang] {
47 | padding: 1em;
48 | margin: .5em 0;
49 | overflow: auto;
50 | }
51 |
52 | :not(pre) > code[class*="lang-"],
53 | pre[data-lang] {
54 | background: #2b2b2b;
55 | }
56 |
57 | /* Inline code */
58 | :not(pre) > code[class*="lang-"] {
59 | padding: .1em;
60 | border-radius: .3em;
61 | }
62 |
63 | .token.comment,
64 | .token.prolog,
65 | .token.cdata {
66 | color: #808080;
67 | }
68 |
69 | .token.delimiter,
70 | .token.boolean,
71 | .token.keyword,
72 | .token.selector,
73 | .token.important,
74 | .token.atrule {
75 | color: #cc7832;
76 | }
77 |
78 | .token.operator,
79 | .token.punctuation,
80 | .token.attr-name {
81 | color: #a9b7c6;
82 | }
83 |
84 | .token.tag,
85 | .token.tag .punctuation,
86 | .token.doctype,
87 | .token.builtin {
88 | color: #e8bf6a;
89 | }
90 |
91 | .token.entity,
92 | .token.number,
93 | .token.symbol {
94 | color: #6897bb;
95 | }
96 |
97 | .token.property,
98 | .token.constant,
99 | .token.variable {
100 | color: #9876aa;
101 | }
102 |
103 | .token.string,
104 | .token.char {
105 | color: #6a8759;
106 | }
107 |
108 | .token.attr-value,
109 | .token.attr-value .punctuation {
110 | color: #a5c261;
111 | }
112 |
113 | .token.attr-value .punctuation:first-child {
114 | color: #a9b7c6;
115 | }
116 |
117 | .token.url {
118 | color: #287bde;
119 | text-decoration: underline;
120 | }
121 |
122 | .token.function {
123 | color: #ffc66d;
124 | }
125 |
126 | .token.regex {
127 | background: #364135;
128 | }
129 |
130 | .token.bold {
131 | font-weight: bold;
132 | }
133 |
134 | .token.italic {
135 | font-style: italic;
136 | }
137 |
138 | .token.inserted {
139 | background: #294436;
140 | }
141 |
142 | .token.deleted {
143 | background: #484a4a;
144 | }
145 |
146 | code.lang-css .token.property,
147 | code.lang-css .token.property + .token.punctuation {
148 | color: #a9b7c6;
149 | }
150 |
151 | code.lang-css .token.id {
152 | color: #ffc66d;
153 | }
154 |
155 | code.lang-css .token.selector > .token.class,
156 | code.lang-css .token.selector > .token.attribute,
157 | code.lang-css .token.selector > .token.pseudo-class,
158 | code.lang-css .token.selector > .token.pseudo-element {
159 | color: #ffc66d;
160 | }
--------------------------------------------------------------------------------
/asset/prism-python.min.js:
--------------------------------------------------------------------------------
1 | Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0},"string-interpolation":{pattern:/(?:f|rf|fr)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:{{)*){(?!{)(?:[^{}]|{(?!{)(?:[^{}]|{(?!{)(?:[^{}])+})+})+}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=}$)/,lookbehind:!0},"conversion-option":{pattern://,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|rb|br)?("""|''')[\s\S]*?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|rb|br)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},function:{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^\s*)@\w+(?:\.\w+)*/im,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:and|as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,boolean:/\b(?:True|False|None)\b/,number:/(?:\b(?=\d)|\B(?=\.))(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i,operator:/[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python,Prism.languages.py=Prism.languages.python;
--------------------------------------------------------------------------------
/asset/right.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/asset/search.min.js:
--------------------------------------------------------------------------------
1 | !function(){var h={},f={EXPIRE_KEY:"docsify.search.expires",INDEX_KEY:"docsify.search.index"};function l(e){var n={"&":"&","<":"<",">":">",'"':""","'":"'"};return String(e).replace(/[&<>"']/g,function(e){return n[e]})}function p(e){return e.text||"table"!==e.type||(e.cells.unshift(e.header),e.text=e.cells.map(function(e){return e.join(" | ")}).join(" |\n ")),e.text}function u(r,e,i,o){void 0===e&&(e="");var s,n=window.marked.lexer(e),c=window.Docsify.slugify,d={};return n.forEach(function(e){if("heading"===e.type&&e.depth<=o){var n=function(e){void 0===e&&(e="");var a={};return{str:e=e&&e.replace(/^'/,"").replace(/'$/,"").replace(/(?:^|\s):([\w-]+:?)=?([\w-%]+)?/g,function(e,n,t){return-1===n.indexOf(":")?(a[n]=t&&t.replace(/"/g,"")||!0,""):e}).trim(),config:a}}(e.text),t=n.str,a=n.config;s=a.id?i.toURL(r,{id:c(a.id)}):i.toURL(r,{id:c(l(e.text))}),d[s]={slug:s,title:t,body:""}}else{if(!s)return;d[s]?d[s].body?(e.text=p(e),d[s].body+="\n"+(e.text||"")):(e.text=p(e),d[s].body=d[s].body?d[s].body+e.text:e.text):d[s]={slug:s,title:"",body:""}}}),c.clear(),d}function c(e){var r=[],i=[];Object.keys(h).forEach(function(n){i=i.concat(Object.keys(h[n]).map(function(e){return h[n][e]}))});var o=(e=e.trim()).split(/[\s\-,\\/]+/);1!==o.length&&(o=[].concat(e,o));function n(e){var n=i[e],s=0,c="",d=n.title&&n.title.trim(),p=n.body&&n.body.trim(),t=n.slug||"";if(d&&(o.forEach(function(e){var n,t=new RegExp(e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&"),"gi"),a=-1;if(n=d?d.search(t):-1,a=p?p.search(t):-1,0<=n||0<=a){s+=0<=n?3:0<=a?2:0,a<0&&(a=0);var r,i=0;i=0==(r=a<11?0:a-10)?70:a+e.length+60,p&&i>p.length&&(i=p.length);var o="..."+l(p).substring(r,i).replace(t,function(e){return''+e+""})+"...";c+=o}}),0\n\n'+e.title+"
\n"+e.content+"
\n\n"}),t.classList.add("show"),a.classList.add("show"),t.innerHTML=s||''+m+"
",d.hideOtherSidebarContent&&(r.classList.add("hide"),i.classList.add("hide"))}function a(e){d=e}function o(e,n){var t=n.router.parse().query.s;a(e),Docsify.dom.style("\n.sidebar {\n padding-top: 0;\n}\n\n.search {\n margin-bottom: 20px;\n padding: 6px;\n border-bottom: 1px solid #eee;\n}\n\n.search .input-wrap {\n display: flex;\n align-items: center;\n}\n\n.search .results-panel {\n display: none;\n}\n\n.search .results-panel.show {\n display: block;\n}\n\n.search input {\n outline: none;\n border: none;\n width: 100%;\n padding: 0 7px;\n line-height: 36px;\n font-size: 14px;\n border: 1px solid transparent;\n}\n\n.search input:focus {\n box-shadow: 0 0 5px var(--theme-color, #42b983);\n border: 1px solid var(--theme-color, #42b983);\n}\n\n.search input::-webkit-search-decoration,\n.search input::-webkit-search-cancel-button,\n.search input {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n}\n.search .clear-button {\n cursor: pointer;\n width: 36px;\n text-align: right;\n display: none;\n}\n\n.search .clear-button.show {\n display: block;\n}\n\n.search .clear-button svg {\n transform: scale(.5);\n}\n\n.search h2 {\n font-size: 17px;\n margin: 10px 0;\n}\n\n.search a {\n text-decoration: none;\n color: inherit;\n}\n\n.search .matching-post {\n border-bottom: 1px solid #eee;\n}\n\n.search .matching-post:last-child {\n border-bottom: 0;\n}\n\n.search p {\n font-size: 14px;\n overflow: hidden;\n text-overflow: ellipsis;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n}\n\n.search p.empty {\n text-align: center;\n}\n\n.app-name.hide, .sidebar-nav.hide {\n display: none;\n}"),function(e){void 0===e&&(e="");var n='\n \n ',t=Docsify.dom.create("div",n),a=Docsify.dom.find("aside");Docsify.dom.toggleClass(t,"search"),Docsify.dom.before(a,t)}(t),function(){var e,n=Docsify.dom.find("div.search"),t=Docsify.dom.find(n,"input"),a=Docsify.dom.find(n,".input-wrap");Docsify.dom.on(n,"click",function(e){return-1===["A","H2","P","EM"].indexOf(e.target.tagName)&&e.stopPropagation()}),Docsify.dom.on(t,"input",function(n){clearTimeout(e),e=setTimeout(function(e){return r(n.target.value.trim())},100)}),Docsify.dom.on(a,"click",function(e){"INPUT"!==e.target.tagName&&(t.value="",r())})}(),t&&setTimeout(function(e){return r(t)},500)}function s(e,n){a(e),function(e,n){var t=Docsify.dom.getNode('.search input[type="search"]');if(t)if("string"==typeof e)t.placeholder=e;else{var a=Object.keys(e).filter(function(e){return-1
2 |
--------------------------------------------------------------------------------
/asset/sidebar.min.css:
--------------------------------------------------------------------------------
1 | .sidebar-nav li{position:relative;margin:0;cursor:pointer}.sidebar-nav ul:not(.app-sub-sidebar)>li:not(.file)::before{content:'';display:block;position:absolute;top:11px;left:-12px;height:6px;width:6px;border-right:1px solid #505d6b;border-bottom:1px solid #505d6b;transform:rotate(-45deg);transition:transform .1s}.sidebar-nav ul:not(.app-sub-sidebar)>li.open::before{transform:rotate(45deg)}.sidebar-nav ul:not(.app-sub-sidebar)>li.collapse::before{transform:rotate(-45deg)}
--------------------------------------------------------------------------------
/asset/style.css:
--------------------------------------------------------------------------------
1 | /*隐藏头部的目录*/
2 | #main>ul:nth-child(1) {
3 | display: none;
4 | }
5 |
6 | #main>ul:nth-child(2) {
7 | display: none;
8 | }
9 |
10 | .markdown-section h1 {
11 | margin: 3rem 0 2rem 0;
12 | }
13 |
14 | .markdown-section h2 {
15 | margin: 2rem 0 1rem;
16 | }
17 |
18 | img,
19 | pre {
20 | border-radius: 8px;
21 | }
22 |
23 | .content,
24 | .sidebar,
25 | .markdown-section,
26 | body,
27 | .search input {
28 | background-color: rgba(243, 242, 238, 1) !important;
29 | }
30 |
31 | @media (min-width:600px) {
32 | .sidebar-toggle {
33 | background-color: #f3f2ee;
34 | }
35 | }
36 |
37 | .docsify-copy-code-button {
38 | background: #f8f8f8 !important;
39 | color: #7a7a7a !important;
40 | }
41 |
42 | body {
43 | /*font-family: Microsoft YaHei, Source Sans Pro, Helvetica Neue, Arial, sans-serif !important;*/
44 | }
45 |
46 | .markdown-section>p {
47 | font-size: 16px !important;
48 | }
49 |
50 | .markdown-section pre>code {
51 | font-family: Consolas, Roboto Mono, Monaco, courier, monospace !important;
52 | font-size: .9rem !important;
53 |
54 | }
55 |
56 | /*.anchor span {
57 | color: rgb(66, 185, 131);
58 | }*/
59 |
60 | section.cover h1 {
61 | margin: 0;
62 | }
63 |
64 | body>section>div.cover-main>ul>li>a {
65 | color: #42b983;
66 | }
67 |
68 | .markdown-section img {
69 | box-shadow: 7px 9px 10px #aaa !important;
70 | }
71 |
72 |
73 | pre {
74 | background-color: #f3f2ee !important;
75 | }
76 |
77 | @media (min-width:600px) {
78 | pre code {
79 | /*box-shadow: 2px 1px 20px 2px #aaa;*/
80 | /*border-radius: 10px !important;*/
81 | padding-left: 20px !important;
82 | }
83 | }
84 |
85 | @media (max-width:600px) {
86 | pre {
87 | padding-left: 0px !important;
88 | padding-right: 0px !important;
89 | }
90 | }
91 |
92 | .markdown-section pre {
93 | padding-left: 0 !important;
94 | padding-right: 0px !important;
95 | box-shadow: 2px 1px 20px 2px #aaa;
96 | }
--------------------------------------------------------------------------------
/asset/sun.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/asset/up.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/docs/10.md:
--------------------------------------------------------------------------------
1 | # Python 字典
2 |
3 | > 原文: [https://thepythonguru.com/python-dictionaries/](https://thepythonguru.com/python-dictionaries/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 字典是一种 python 数据类型,用于存储键值对。 它使您可以使用键快速检索,添加,删除,修改值。 字典与我们在其他语言上称为关联数组或哈希的非常相似。
12 |
13 | **注意**:
14 |
15 | 字典是可变的。
16 |
17 | ## 创建字典
18 |
19 | * * *
20 |
21 | 可以使用一对大括号(`{}`)创建字典。 字典中的每个项目都由一个键,一个冒号,一个值组成。 每个项目都用逗号(`,`)分隔。 让我们举个例子。
22 |
23 | ```py
24 | friends = {
25 | 'tom' : '111-222-333',
26 | 'jerry' : '666-33-111'
27 | }
28 |
29 | ```
30 |
31 | 这里`friends`是有两个项目的字典。 需要注意的一点是,键必须是可哈希的类型,但是值可以是任何类型。 字典中的每个键都必须是唯一的。
32 |
33 | ```py
34 | >>> dict_emp = {} # this will create an empty dictionary
35 |
36 | ```
37 |
38 | ## 检索,修改和向字典中添加元素
39 |
40 | * * *
41 |
42 | 要从字典中获取项目,请使用以下语法:
43 |
44 | ```py
45 | >>> dictionary_name['key']
46 |
47 | ```
48 |
49 | ```py
50 | >>> friends['tom']
51 | '111-222-333'
52 |
53 | ```
54 |
55 | 如果字典中存在键,则将返回值,否则将引发`KeyError`异常。 要添加或修改项目,请使用以下语法:
56 |
57 | ```py
58 | >>> dictionary_name['newkey'] = 'newvalue'
59 |
60 | ```
61 |
62 | ```py
63 | >>> friends['bob'] = '888-999-666'
64 | >>> friends
65 | {'tom': '111-222-333', 'bob': '888-999-666', 'jerry': '666-33-111'}
66 |
67 | ```
68 |
69 | ## 从字典中删除项目
70 |
71 | * * *
72 |
73 | ```py
74 | >>> del dictionary_name['key']
75 |
76 | ```
77 |
78 | ```py
79 | >>> del friends['bob']
80 | >>> friends
81 | {'tom': '111-222-333', 'jerry': '666-33-111'}
82 |
83 | ```
84 |
85 | 如果找到键,则该项目将被删除,否则将抛出`KeyError`异常。
86 |
87 | ## 遍历字典中的项目
88 |
89 | * * *
90 |
91 | 您可以使用`for`循环遍历字典中的元素。
92 |
93 | ```py
94 | >>> friends = {
95 | ... 'tom' : '111-222-333',
96 | ... 'jerry' : '666-33-111'
97 | ...}
98 | >>>
99 | >>> for key in friends:
100 | ... print(key, ":", friends[key])
101 | ...
102 | tom : 111-222-333
103 | jerry : 666-33-111
104 | >>>
105 | >>>
106 |
107 | ```
108 |
109 | ## 查找字典的长度
110 |
111 | * * *
112 |
113 | 您可以使用`len()`函数查找字典的长度。
114 |
115 | ```py
116 | >>> len(friends)
117 | 2
118 |
119 | ```
120 |
121 | ## `in`和`not in`运算符
122 |
123 | * * *
124 |
125 | `in`和`not in`运算符检查字典中是否存在键。
126 |
127 | ```py
128 | >>> 'tom' in friends
129 | True
130 | >>> 'tom' not in friends
131 | False
132 |
133 | ```
134 |
135 | ## 字典中的相等测试
136 |
137 | * * *
138 |
139 | `==`和`!=`运算符告诉字典是否包含相同的项目。
140 |
141 | ```py
142 | >>> d1 = {"mike":41, "bob":3}
143 | >>> d2 = {"bob":3, "mike":41}
144 | >>> d1 == d2
145 | True
146 | >>> d1 != d2
147 | False
148 | >>>
149 |
150 | ```
151 |
152 | **注意**:
153 |
154 | 您不能使用`<`,`>`,`>=`,`<=`等其他关系运算符来比较字典。
155 |
156 | ## 字典方法
157 |
158 | * * *
159 |
160 | Python 提供了几种内置的方法来处理字典。
161 |
162 | | 方法 | 描述 |
163 | | --- | --- |
164 | | `popitem()` | 返回字典中随机选择的项目,并删除所选项目。 |
165 | | `clear()` | 删除字典中的所有内容 |
166 | | `keys()` | 以元组形式返回字典中的键 |
167 | | `values()` | 以元组形式返回字典中的值 |
168 | | `get(key)` | 键的返回值,如果找不到键,则返回`None`,而不是引发`KeyError`异常 |
169 | | `pop(key)` | 从字典中删除该项目,如果找不到该键,则会抛出`KeyError` |
170 |
171 | ```py
172 | >>> friends = {'tom': '111-222-333', 'bob': '888-999-666', 'jerry': '666-33-111'}
173 | >>>
174 | >>> friends.popitem()
175 | ('tom', '111-222-333')
176 | >>>
177 | >>> friends.clear()
178 | >>>
179 | >>> friends
180 | {}
181 | >>>
182 | >>> friends = {'tom': '111-222-333', 'bob': '888-999-666', 'jerry': '666-33-111'}
183 | >>>
184 | >>> friends.keys()
185 | dict_keys(['tom', 'bob', 'jerry'])
186 | >>>
187 | >>> friends.values()
188 | dict_values(['111-222-333', '888-999-666', '666-33-111'])
189 | >>>
190 | >>> friends.get('tom')
191 | '111-222-333'
192 | >>>
193 | >>> friends.get('mike', 'Not Exists')
194 | 'Not Exists'
195 | >>>
196 | >>> friends.pop('bob')
197 | '888-999-666'
198 | >>>
199 | >>> friends
200 | {'tom': '111-222-333', 'jerry': '666-33-111'}
201 |
202 | ```
203 |
204 | 在下一篇文章中,我们将学习 [Python 元组](/python-tuples/)。
205 |
206 | * * *
207 |
208 | * * *
--------------------------------------------------------------------------------
/docs/11.md:
--------------------------------------------------------------------------------
1 | # Python 元组
2 |
3 | > 原文: [https://thepythonguru.com/python-tuples/](https://thepythonguru.com/python-tuples/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 在 Python 中,元组与列表非常相似,但是一旦创建了元组,就无法添加,删除,替换和重新排序元素。
12 |
13 | **注意**:
14 |
15 | 元组是不可变的。
16 |
17 | ## 创建一个元组
18 |
19 | * * *
20 |
21 | ```py
22 | >>> t1 = () # creates an empty tuple with no data
23 | >>>
24 | >>> t2 = (11,22,33)
25 | >>>
26 | >>> t3 = tuple([1,2,3,4,4]) # tuple from array
27 | >>>
28 | >>> t4 = tuple("abc") # tuple from string
29 |
30 | ```
31 |
32 | ## 元组函数
33 |
34 | * * *
35 |
36 | 元组也可以使用`max()`,`min()`,`len()`和`sum()`之类的函数。
37 |
38 | ```py
39 | >>> t1 = (1, 12, 55, 12, 81)
40 | >>> min(t1)
41 | 1
42 | >>> max(t1)
43 | 81
44 | >>> sum(t1)
45 | 161
46 | >>> len(t1)
47 | 5
48 |
49 | ```
50 |
51 | ## 元组迭代
52 |
53 | * * *
54 |
55 | 元组可使用`for`循环进行迭代,[在此处了解有关 for 循环的更多信息](/python-loops/)。
56 |
57 | ```py
58 | >>> t = (11,22,33,44,55)
59 | >>> for i in t:
60 | ... print(i, end=" ")
61 | >>> 11 22 33 44 55
62 |
63 | ```
64 |
65 | ## 元组切片
66 |
67 | * * *
68 |
69 | 切片运算符在元组中的作用与在列表和字符串中的作用相同。
70 |
71 | ```py
72 | >>> t = (11,22,33,44,55)
73 | >>> t[0:2]
74 | (11,22)
75 |
76 | ```
77 |
78 | ## `in`和`not in`运算符
79 |
80 | * * *
81 |
82 | 您可以使用`in`和`not in`运算符检查元组中项的存在,如下所示。
83 |
84 | ```py
85 | >>> t = (11,22,33,44,55)
86 | >>> 22 in t
87 | True
88 | >>> 22 not in t
89 | False
90 |
91 | ```
92 |
93 | 在下一章中,我们将学习 [python 数据类型转换](/datatype-conversion/)。
94 |
95 | * * *
96 |
97 | * * *
--------------------------------------------------------------------------------
/docs/12.md:
--------------------------------------------------------------------------------
1 | # 数据类型转换
2 |
3 | > 原文: [https://thepythonguru.com/datatype-conversion/](https://thepythonguru.com/datatype-conversion/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 偶尔,您会希望将一种类型的数据类型转换为另一种类型。 数据类型转换也称为类型转换。
12 |
13 | ## 将`int`转换为`float`
14 |
15 | * * *
16 |
17 | 要将`int`转换为`float`,可以使用`float()`函数。
18 |
19 | ```py
20 | >>> i = 10
21 | >>> float(i)
22 | 10.0
23 |
24 | ```
25 |
26 | ## 将`float`转换为`int`
27 |
28 | * * *
29 |
30 | 要将`float`转换为`int`,您需要使用`int()`函数。
31 |
32 | ```py
33 | >>> f = 14.66
34 | >>> int(f)
35 | 14
36 |
37 | ```
38 |
39 | ## 将字符串转换为`int`
40 |
41 | * * *
42 |
43 | 要将`string`转换为`int`,请使用`int()`函数。
44 |
45 | ```py
46 | >>> s = "123"
47 | >>> int(s)
48 | 123
49 |
50 | ```
51 |
52 | **提示**:
53 |
54 | 如果字符串包含非数字字符,则`int()`将引发`ValueError`异常。
55 |
56 | ## 将数字转换为字符串
57 |
58 | * * *
59 |
60 | 要将数字转换为字符串,请使用`str()`函数。
61 |
62 | ```py
63 | >>> i = 100
64 | >>> str(i)
65 | "100"
66 | >>> f = 1.3
67 | str(f)
68 | '1.3'
69 |
70 | ```
71 |
72 | ## 舍入数字
73 |
74 | * * *
75 |
76 | 四舍五入数字是通过`round()`函数完成的。
77 |
78 | **语法**:`round(number[, ndigits])`
79 |
80 | ```py
81 | >>> i = 23.97312
82 | >>> round(i, 2)
83 | 23.97
84 |
85 | ```
86 |
87 | 接下来,我们将介绍[控制语句](/python-control-statements/)。
88 |
89 | * * *
90 |
91 | * * *
--------------------------------------------------------------------------------
/docs/13.md:
--------------------------------------------------------------------------------
1 | # Python 控制语句
2 |
3 | > 原文: [https://thepythonguru.com/python-control-statements/](https://thepythonguru.com/python-control-statements/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 程序根据某些条件执行语句是很常见的。 在本节中,我们将了解 Python 中的`if else`语句。
12 |
13 | 但是在我们需要了解关系运算符之前。 关系运算符使我们可以比较两个对象。
14 |
15 | | 符号 | 描述 |
16 | | --- | --- |
17 | | `<=` | 小于或等于 |
18 | | `<` | 小于 |
19 | | `>` | 大于 |
20 | | `>=` | 大于或等于 |
21 | | `==` | 等于 |
22 | | `!=` | 不等于 |
23 |
24 | 比较的结果将始终为布尔值,即`True`或`False`。 请记住,`True`和`False`是用于表示布尔值的 python 关键字。
25 |
26 | 让我们举一些例子:
27 |
28 | ```py
29 | >>> 3 == 4
30 | False
31 | >>> 12 > 3
32 | True
33 | >>> 12 == 12
34 | True
35 | >>> 44 != 12
36 | True
37 |
38 | ```
39 |
40 | 现在您可以处理`if`语句了。 `if`语句的语法如下所示:
41 |
42 | ```py
43 | if boolean-expression:
44 | #statements
45 | else:
46 | #statements
47 |
48 | ```
49 |
50 | **注意**:
51 |
52 | `if`块中的每个语句都必须使用相同数量的空格缩进,否则将导致语法错误。 这与 Java,C,C# 等使用花括号(`{}`)的语言完全不同。
53 |
54 | 现在来看一个例子
55 |
56 | ```py
57 | i = 10
58 |
59 | if i % 2 == 0:
60 | print("Number is even")
61 | else:
62 | print("Number is odd")
63 |
64 | ```
65 |
66 | 在这里您可以看到,如果数字为偶数,则将打印`"Number is even"`。 否则打印`"Number is odd"`。
67 |
68 | **注意**:
69 |
70 | `else`子句是可选的,您可以根据需要仅使用`if`子句,如下所示:
71 |
72 | ```py
73 | if today == "party":
74 | print("thumbs up!")
75 |
76 | ```
77 |
78 | 在此,如果`today`的值为`"party"`,则将打印`thumbs up!`,否则将不打印任何内容。
79 |
80 | 如果您的程序需要检查一长串条件,那么您需要使用`if-elif-else`语句。
81 |
82 | ```py
83 | if boolean-expression:
84 | #statements
85 | elif boolean-expression:
86 | #statements
87 | elif boolean-expression:
88 | #statements
89 | elif boolean-expression:
90 | #statements
91 | else:
92 | #statements
93 |
94 | ```
95 |
96 | 您可以根据程序要求添加`elif`条件。
97 |
98 | 这是一个说明`if-elif-else`语句的示例。
99 |
100 | ```py
101 | today = "monday"
102 |
103 | if today == "monday":
104 | print("this is monday")
105 | elif today == "tuesday":
106 | print("this is tuesday")
107 | elif today == "wednesday":
108 | print("this is wednesday")
109 | elif today == "thursday":
110 | print("this is thursday")
111 | elif today == "friday":
112 | print("this is friday")
113 | elif today == "saturday":
114 | print("this is saturday")
115 | elif today == "sunday":
116 | print("this is sunday")
117 | else:
118 | print("something else")
119 |
120 | ```
121 |
122 | ## 嵌套`if`语句
123 |
124 | * * *
125 |
126 | 您可以将`if`语句嵌套在另一个`if`语句中,如下所示:
127 |
128 | ```py
129 | today = "holiday"
130 | bank_balance = 25000
131 | if today == "holiday":
132 | if bank_balance > 20000:
133 | print("Go for shopping")
134 | else:
135 | print("Watch TV")
136 | else:
137 | print("normal working day")
138 |
139 | ```
140 |
141 | 在下一篇文章中,我们将学习 [Python 函数](/python-functions/)。
142 |
143 | * * *
144 |
145 | * * *
--------------------------------------------------------------------------------
/docs/14.md:
--------------------------------------------------------------------------------
1 | # Python 函数
2 |
3 | > 原文: [https://thepythonguru.com/python-functions/](https://thepythonguru.com/python-functions/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 函数是可重用的代码段,可帮助我们组织代码的结构。 我们创建函数,以便我们可以在程序中多次运行一组语句,而无需重复自己。
12 |
13 | ## 创建函数
14 |
15 | * * *
16 |
17 | Python 使用`def`关键字启动函数,以下是语法:
18 |
19 | ```py
20 | def function_name(arg1, arg2, arg3, .... argN):
21 | #statement inside function
22 |
23 | ```
24 |
25 | **注意**:
26 |
27 | 函数内的所有语句均应使用相等的空格缩进。 函数可以接受零个或多个括在括号中的参数(也称为参数)。 您也可以使用`pass`关键字来省略函数的主体,如下所示:
28 |
29 | ```py
30 | def myfunc():
31 | pass
32 |
33 | ```
34 |
35 | 让我们来看一个例子。
36 |
37 | ```py
38 | def sum(start, end):
39 | result = 0
40 | for i in range(start, end + 1):
41 | result += i
42 | print(result)
43 |
44 | sum(10, 50)
45 |
46 | ```
47 |
48 | **预期输出**:
49 |
50 | ```py
51 | 1230
52 |
53 | ```
54 |
55 | 上面我们定义了一个名为`sum()`的函数,它具有两个参数`start`和`end`。 该函数计算从`start`到`end`开始的所有数字的总和。
56 |
57 | ## 具有返回值的函数。
58 |
59 | * * *
60 |
61 | 上面的函数只是将结果打印到控制台,如果我们想将结果分配给变量以进行进一步处理怎么办? 然后,我们需要使用`return`语句。 `return`语句将结果发送回调用方并退出该函数。
62 |
63 | ```py
64 | def sum(start, end):
65 | result = 0
66 | for i in range(start, end + 1):
67 | result += i
68 | return result
69 |
70 | s = sum(10, 50)
71 | print(s)
72 |
73 | ```
74 |
75 | **预期输出**:
76 |
77 | ```py
78 | 1230
79 |
80 | ```
81 |
82 | 在这里,我们使用`return`语句返回数字总和并将其分配给变量`s`。
83 |
84 | 您也可以使用`return`陈述式而没有返回值。
85 |
86 | ```py
87 | def sum(start, end):
88 | if(start > end):
89 | print("start should be less than end")
90 | return # here we are not returning any value so a special value None is returned
91 | result = 0
92 | for i in range(start, end + 1):
93 | result += i
94 | return result
95 |
96 | s = sum(110, 50)
97 | print(s)
98 |
99 | ```
100 |
101 | **预期输出**:
102 |
103 | ```py
104 | start should be less than end
105 | None
106 |
107 | ```
108 |
109 | 在 python 中,如果您未从函数显式返回值,则始终会返回特殊值`None`。 让我们举个例子:
110 |
111 | ```py
112 | def test(): # test function with only one statement
113 | i = 100
114 | print(test())
115 |
116 | ```
117 |
118 | **预期输出**:
119 |
120 | ```py
121 | None
122 |
123 | ```
124 |
125 | 如您所见,`test()`函数没有显式返回任何值,因此返回了`None`。
126 |
127 | ## 全局变量与局部变量
128 |
129 | * * *
130 |
131 | **全局变量**:未绑定到任何函数但可以在函数内部和外部访问的变量称为全局变量。
132 |
133 | **局部变量**:在函数内部声明的变量称为局部变量。
134 |
135 | 让我们看一些例子来说明这一点。
136 |
137 | **示例 1** :
138 |
139 | ```py
140 | global_var = 12 # a global variable
141 |
142 | def func():
143 | local_var = 100 # this is local variable
144 | print(global_var) # you can access global variables in side function
145 |
146 | func() # calling function func()
147 |
148 | #print(local_var) # you can't access local_var outside the function, because as soon as function ends local_var is destroyed
149 |
150 | ```
151 |
152 | **预期输出**:
153 |
154 | ```py
155 | 12
156 |
157 | ```
158 |
159 | **示例 2**:
160 |
161 | ```py
162 | xy = 100
163 |
164 | def cool():
165 | xy = 200 # xy inside the function is totally different from xy outside the function
166 | print(xy) # this will print local xy variable i.e 200
167 |
168 | cool()
169 |
170 | print(xy) # this will print global xy variable i.e 100
171 |
172 | ```
173 |
174 | **预期输出**:
175 |
176 | ```py
177 | 200
178 | 100
179 |
180 | ```
181 |
182 | 您可以使用`global`关键字后跟逗号分隔的变量名称(`,`)在全局范围内绑定局部变量。
183 |
184 | ```py
185 | t = 1
186 |
187 | def increment():
188 | global t # now t inside the function is same as t outside the function
189 | t = t + 1
190 | print(t) # Displays 2
191 |
192 | increment()
193 | print(t) # Displays 2
194 |
195 | ```
196 |
197 | **预期输出**:
198 |
199 | ```py
200 | 2
201 | 2
202 |
203 | ```
204 |
205 | 请注意,在全局声明变量时不能为变量赋值。
206 |
207 | ```py
208 | t = 1
209 |
210 | def increment():
211 | #global t = 1 # this is error
212 | global t
213 | t = 100 # this is okay
214 | t = t + 1
215 | print(t) # Displays 101
216 |
217 | increment()
218 | print(t) # Displays 101
219 |
220 | ```
221 |
222 | **预期输出**:
223 |
224 | ```py
225 | 101
226 | 101
227 |
228 | ```
229 |
230 | 实际上,无需在函数外部声明全局变量。 您可以在函数内部全局声明它们。
231 |
232 | ```py
233 | def foo():
234 | global x # x is declared as global so it is available outside the function
235 | x = 100
236 |
237 | foo()
238 | print(x)
239 |
240 | ```
241 |
242 | **预期输出**: 100
243 |
244 | ## 具有默认值的参数
245 |
246 | * * *
247 |
248 | 要指定参数的默认值,您只需要使用赋值运算符分配一个值。
249 |
250 | ```py
251 | def func(i, j = 100):
252 | print(i, j)
253 |
254 | ```
255 |
256 | 以上函数具有两个参数`i`和`j`。 参数`j`的默认值为`100`,这意味着我们可以在调用函数时忽略`j`的值。
257 |
258 | ```py
259 | func(2) # here no value is passed to j, so default value will be used
260 |
261 | ```
262 |
263 | **预期输出**:
264 |
265 | ```py
266 | 2 100
267 |
268 | ```
269 |
270 | 再次调用`func()`函数,但这一次为`j`参数提供一个值。
271 |
272 | ```py
273 | func(2, 300) # here 300 is passed as a value of j, so default value will not be used
274 |
275 | ```
276 |
277 | **预期输出**:
278 |
279 | ```py
280 | 2 300
281 |
282 | ```
283 |
284 | ## 关键字参数
285 |
286 | * * *
287 |
288 | 有两种方法可以将参数传递给方法:位置参数和关键字参数。 在上一节中,我们已经看到了位置参数的工作方式。 在本节中,我们将学习关键字参数。
289 |
290 | 关键字参数允许您使用像`name=value`这样的名称值对来传递每个参数。 让我们举个例子:
291 |
292 | ```py
293 | def named_args(name, greeting):
294 | print(greeting + " " + name )
295 |
296 | ```
297 |
298 | ```py
299 | named_args(name='jim', greeting='Hello')
300 |
301 | named_args(greeting='Hello', name='jim') # you can pass arguments this way too
302 |
303 | ```
304 |
305 | **期望值**:
306 |
307 | ```py
308 | Hello jim
309 | Hello jim
310 |
311 | ```
312 |
313 | ## 混合位置和关键字参数
314 |
315 | * * *
316 |
317 | 可以混合使用位置参数和关键字参数,但是对于此位置参数必须出现在任何关键字参数之前。 我们来看一个例子。
318 |
319 | ```py
320 | def my_func(a, b, c):
321 | print(a, b, c)
322 |
323 | ```
324 |
325 | 您可以通过以下方式调用上述函数。
326 |
327 | ```py
328 | # using positional arguments only
329 | my_func(12, 13, 14)
330 |
331 | # here first argument is passed as positional arguments while other two as keyword argument
332 | my_func(12, b=13, c=14)
333 |
334 | # same as above
335 | my_func(12, c=13, b=14)
336 |
337 | # this is wrong as positional argument must appear before any keyword argument
338 | # my_func(12, b=13, 14)
339 |
340 | ```
341 |
342 | **预期输出**:
343 |
344 | ```py
345 | 12 13 14
346 | 12 13 14
347 | 12 14 13
348 |
349 | ```
350 |
351 | ## 从函数返回多个值
352 |
353 | * * *
354 |
355 | 我们可以使用`return`语句从函数中返回多个值,方法是用逗号(`,`)分隔它们。 多个值作为元组返回。
356 |
357 | ```py
358 | def bigger(a, b):
359 | if a > b:
360 | return a, b
361 | else:
362 | return b, a
363 |
364 | s = bigger(12, 100)
365 | print(s)
366 | print(type(s))
367 |
368 | ```
369 |
370 | **预期输出**:
371 |
372 | ```py
373 | (100, 12)
374 |
375 |
376 | ```
377 |
378 | 在下一篇文章中,我们将学习 [Python 循环](/python-loops/)
379 |
380 | * * *
381 |
382 | * * *
--------------------------------------------------------------------------------
/docs/15.md:
--------------------------------------------------------------------------------
1 | # Python 循环
2 |
3 | > 原文: [https://thepythonguru.com/python-loops/](https://thepythonguru.com/python-loops/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | Python 只有两个循环:
12 |
13 | 1. `for`循环
14 | 2. `while`循环
15 |
16 | ## `for`循环
17 |
18 | * * *
19 |
20 | `for`循环语法:
21 |
22 | ```py
23 | for i in iterable_object:
24 | # do something
25 |
26 | ```
27 |
28 | **注意**:
29 |
30 | `for`和`while`循环内的所有语句必须缩进相同的空格数。 否则,将抛出`SyntaxError`。
31 |
32 | 让我们举个例子
33 |
34 | ```py
35 | my_list = [1,2,3,4]
36 |
37 | for i in my_list:
38 | print(i)
39 |
40 | ```
41 |
42 | **预期输出**:
43 |
44 | ```py
45 | 1
46 | 2
47 | 3
48 | 4
49 |
50 | ```
51 |
52 | 这是`for`循环的工作方式:
53 |
54 | 在第一次迭代中,为`i`分配了值`1`,然后执行了`print`语句。 在第二次迭代中,为`i`赋值`2`,然后再次执行`print`语句。 此过程将继续进行,直到列表中没有其他元素并且存在`for`循环为止。
55 |
56 | ## `range(a, b)`函数
57 |
58 | * * *
59 |
60 | `range(a, b)`函数从`a`,`a + 1`,`a+ 2` ....,`b - 2`和`b - 1`返回整数序列。 例如:
61 |
62 | ```py
63 | for i in range(1, 10):
64 | print(i)
65 |
66 | ```
67 |
68 | **预期输出**:
69 |
70 | ```py
71 | 1
72 | 2
73 | 3
74 | 4
75 | 5
76 | 6
77 | 7
78 | 8
79 | 9
80 |
81 | ```
82 |
83 | 您还可以通过仅提供一个参数来使用`range()`函数,如下所示:
84 |
85 | ```py
86 | >>> for i in range(10):
87 | ... print(i)
88 |
89 | 0
90 | 1
91 | 2
92 | 3
93 | 4
94 | 5
95 | 6
96 | 7
97 | 8
98 | 9
99 |
100 | ```
101 |
102 | 循环打印的范围是 0 到 9。
103 |
104 | `range(a, b)`函数具有可选的第三个参数,用于指定步长。 例如:
105 |
106 | ```py
107 | for i in range(1, 20, 2):
108 | print(i)
109 |
110 | ```
111 |
112 | **预期输出**:
113 |
114 | ```py
115 | 1
116 | 3
117 | 5
118 | 7
119 | 9
120 | 11
121 | 13
122 | 15
123 | 17
124 | 19
125 |
126 | ```
127 |
128 | ## `While`循环
129 |
130 | * * *
131 |
132 | 句法:
133 |
134 | ```py
135 | while condition:
136 | # do something
137 |
138 | ```
139 |
140 | `while`循环在其中继续执行语句,直到条件变为假。 在每次迭代条件检查之后,如果其条件为`True`,则会在`while`循环中再次执行语句。
141 |
142 | 让我们举个例子:
143 |
144 | ```py
145 | count = 0
146 |
147 | while count < 10:
148 | print(count)
149 | count += 1
150 |
151 | ```
152 |
153 | **预期输出**:
154 |
155 | ```py
156 | 0
157 | 1
158 | 2
159 | 3
160 | 4
161 | 5
162 | 6
163 | 7
164 | 8
165 | 9
166 |
167 | ```
168 |
169 | 在此处,将继续打印,直到`count`小于`10`为止。
170 |
171 | ## `break`语句
172 |
173 | * * *
174 |
175 | `break`语句允许突破循环。
176 |
177 | ```py
178 | count = 0
179 |
180 | while count < 10:
181 | count += 1
182 | if count == 5:
183 | break
184 | print("inside loop", count)
185 |
186 | print("out of while loop")
187 |
188 | ```
189 |
190 | 当`count`等于`5`时,如果条件求值为`True`,并且`break`关键字跳出循环。
191 |
192 | **预期输出**:
193 |
194 | ```py
195 | inside loop 1
196 | inside loop 2
197 | inside loop 3
198 | inside loop 4
199 | out of while loop
200 |
201 | ```
202 |
203 | ## `continue`语句
204 |
205 | * * *
206 |
207 | 当在循环中遇到`continue`语句时,它将结束当前迭代,并且程序控制将转到循环主体的末尾。
208 |
209 | ```py
210 | count = 0
211 |
212 | while count < 10:
213 | count += 1
214 | if count % 2 == 0:
215 | continue
216 | print(count)
217 |
218 | ```
219 |
220 | **预期输出**:
221 |
222 | ```py
223 | 1
224 | 3
225 | 5
226 | 7
227 | 9
228 |
229 | ```
230 |
231 | 如您所见,当`count % 2 == 0`时,将执行`continue`语句,该语句导致当前迭代结束,并且控件继续进行下一个迭代。
232 |
233 | 在下一课中,我们将学习 [Python 数学函数](/python-mathematical-function/)。
234 |
235 | * * *
236 |
237 | * * *
--------------------------------------------------------------------------------
/docs/16.md:
--------------------------------------------------------------------------------
1 | # Python 数学函数
2 |
3 | > 原文: [https://thepythonguru.com/python-mathematical-function/](https://thepythonguru.com/python-mathematical-function/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | Python 具有许多内置函数。
12 |
13 | | 方法 | 描述 |
14 | | --- | --- |
15 | | `round(number[, ndigits])` | 四舍五入数字,也可以在第二个参数中指定精度 |
16 | | `pow(a, b)` | 将`a`提升到`b`的幂 |
17 | | `abs(x)` | 返回`x`的绝对值 |
18 | | `max(x1, x2, ..., xn)` | 返回提供的参数中的最大值 |
19 | | `min(x1, x2, ..., xn)` | 返回提供的参数中的最小值 |
20 |
21 | 下面提到的函数位于`math`模块中,因此您需要使用以下行首先导入`math`模块。
22 |
23 | ```py
24 | import math
25 |
26 | ```
27 |
28 | | 方法 | 描述 |
29 | | --- | --- |
30 | | `ceil(x)` | 此函数将数字四舍五入并返回其最接近的整数 |
31 | | `floor(x)` | 此函数将向下取整并返回其最接近的整数 |
32 | | `sqrt(x)` | 返回数字的平方根 |
33 | | `sin(x)` | 返回`x`的正弦,其中`x`以弧度表示 |
34 | | `cos(x)` | 返回`x`的余弦值,其中`x`为弧度 |
35 | | `tan(x)` | 返回`x`的切线,其中`x`为弧度 |
36 |
37 | 让我们举一些例子来更好地理解
38 |
39 | ```py
40 | >>> abs(-22) # Returns the absolute value
41 | 22
42 | >>>
43 | >>> max(9, 3, 12, 81) # Returns the maximum number
44 | 81
45 | >>>
46 | >>> min(78, 99, 12, 32) # Returns the minimum number
47 | 12
48 | >>>
49 | >>> pow(8, 2) # can also be written as 8 ** 2
50 | 64
51 | >>>
52 | >>> pow(4.1, 3.2) # can also be written as 4.1 ** 3.2
53 | 91.39203368671122
54 | >>>
55 | >>> round(5.32) # Rounds to its nearest integer
56 | 5
57 | >>>
58 | >>> round(3.1456875712, 3) # Return number with 3 digits after decimal point
59 | 3.146
60 |
61 | ```
62 |
63 | ```py
64 | >>> import math
65 | >>> math.ceil(3.4123)
66 | 4
67 | >>> math.floor(24.99231)
68 | 24
69 |
70 | ```
71 |
72 | 在下一篇文章中,我们将学习[如何在 python](/python-generating-random-numbers/) 中生成随机数。
73 |
74 | * * *
75 |
76 | * * *
--------------------------------------------------------------------------------
/docs/17.md:
--------------------------------------------------------------------------------
1 | # Python 生成随机数
2 |
3 | > 原文: [https://thepythonguru.com/python-generating-random-numbers/](https://thepythonguru.com/python-generating-random-numbers/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | Python `random`模块包含生成随机数的函数。 因此,首先需要使用以下行导入`random`模块。
12 |
13 | ```py
14 | import random
15 |
16 | ```
17 |
18 | ## `random()`函数
19 |
20 | * * *
21 |
22 | `random()`函数返回随机数`r`,使得`0 <= r < 1.0`。
23 |
24 | ```py
25 | >>> import random
26 | >>> for i in range(0, 10):
27 | ... print(random.random())
28 | ...
29 |
30 | ```
31 |
32 | **预期输出**:
33 |
34 | ```py
35 | 0.9240468209780505
36 | 0.14200320177446257
37 | 0.8647635207997064
38 | 0.23926674191769448
39 | 0.4436673317102027
40 | 0.09211695432442013
41 | 0.2512541244937194
42 | 0.7279402864974873
43 | 0.3864708801092763
44 | 0.08450122561765672
45 |
46 | ```
47 |
48 | `randint(a, b)`生成`a`和`b`(含)之间的随机数。
49 |
50 | ```py
51 | >>> import random
52 | >>> for i in range(0, 10):
53 | ... print(random.randint(1, 10))
54 | ...
55 |
56 | 8
57 | 3
58 | 4
59 | 7
60 | 1
61 | 5
62 | 3
63 | 7
64 | 3
65 | 3
66 |
67 | ```
68 |
69 | 下一章将介绍 python 中的[文件处理技术](/python-file-handling/)。
70 |
71 | * * *
72 |
73 | * * *
--------------------------------------------------------------------------------
/docs/18.md:
--------------------------------------------------------------------------------
1 | # Python 文件处理
2 |
3 | > 原文: [https://thepythonguru.com/python-file-handling/](https://thepythonguru.com/python-file-handling/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 我们可以使用文件处理来读写文件中的数据。
12 |
13 | ## 打开文件
14 |
15 | * * *
16 |
17 | 在读/写之前,您首先需要打开文件。 打开文件的语法是。
18 |
19 | ```py
20 | f = open(filename, mode)
21 |
22 | ```
23 |
24 | `open()`函数接受两个参数`filename`和`mode`。 `filename`是一个字符串参数,用于指定文件名及其路径,而`mode`也是一个字符串参数,用于指定文件的使用方式,即用于读取或写入。 `f`是文件处理器对象,也称为文件指针。
25 |
26 | ## 关闭文件
27 |
28 | * * *
29 |
30 | 读/写完文件后,您需要使用`close()`这样的方法关闭文件,
31 |
32 | ```py
33 | f.close() # where f is a file pointer
34 |
35 | ```
36 |
37 | ## 打开文件的不同模式
38 |
39 | * * *
40 |
41 | | 模式 | 描述 |
42 | | --- | --- |
43 | | `"r"` | 打开文件以只读 |
44 | | `"w"` | 打开文件进行写入。 如果文件已经存在,则在打开之前将清除其数据。 否则将创建新文件 |
45 | | `"a"` | 以附加模式打开文件,即将数据写入文件末尾 |
46 | | `"wb"` | 打开文件以二进制模式写入 |
47 | | `"rb"` | 打开文件以二进制模式读取 |
48 |
49 | 现在让我们看一些示例。
50 |
51 | ## 将数据写入文件
52 |
53 | * * *
54 |
55 | ```py
56 | >>> f = open('myfile.txt', 'w') # open file for writing
57 | >>> f.write('this first line\n') # write a line to the file
58 | >>> f.write('this second line\n') # write one more line to the file
59 | >>> f.close() # close the file
60 |
61 | ```
62 |
63 | **注意**:
64 |
65 | `write()`方法不会像`print()`函数那样自动插入新行(`'\n'`),需要显式添加`'\n'`来编写`write()`方法。
66 |
67 | ## 从文件读取数据
68 |
69 | * * *
70 |
71 | 要从文件读回数据,您需要以下三种方法之一。
72 |
73 | | 方法 | 描述 |
74 | | --- | --- |
75 | | `read([number])` | 从文件中返回指定数量的字符。 如果省略,它将读取文件的全部内容。 |
76 | | `readline()` | 返回文件的下一行。 |
77 | | `readlines()` | 读取所有行作为文件中的字符串列表 |
78 |
79 | ## 一次读取所有数据
80 |
81 | * * *
82 |
83 | ```py
84 | >>> f = open('myfile.txt', 'r')
85 | >>> f.read() # read entire content of file at once
86 | "this first line\nthis second line\n"
87 | >>> f.close()
88 |
89 | ```
90 |
91 | 将所有行读取为数组。
92 |
93 | ```py
94 | >>> f = open('myfile.txt', 'r')
95 | >>> f.readlines() # read entire content of file at once
96 | ["this first line\n", "this second line\n"]
97 | >>> f.close()
98 |
99 | ```
100 |
101 | 只读一行。
102 |
103 | ```py
104 | >>> f = open('myfile.txt', 'r')
105 | >>> f.readline() # read the first line
106 | "this first line\n"
107 | >>> f.close()
108 |
109 | ```
110 |
111 | ## 附加数据
112 |
113 | * * *
114 |
115 | 要附加数据,您需要以`'a'`模式打开文件。
116 |
117 | ```py
118 | >>> f = open('myfile.txt', 'a')
119 | >>> f.write("this is third line\n")
120 | 19
121 | >>> f.close()
122 |
123 | ```
124 |
125 | ## 使用`for`循环遍历数据
126 |
127 | * * *
128 |
129 | 您可以使用文件指针遍历文件。
130 |
131 | ```py
132 | >>> f = open('myfile.txt', 'r')
133 | >>> for line in f:
134 | ... print(line)
135 | ...
136 | this first line
137 | this second line
138 | this is third line
139 |
140 | >>> f.close()
141 |
142 | ```
143 |
144 | ## 二进制读写
145 |
146 | * * *
147 |
148 | 要执行二进制 I/O,您需要使用一个名为`pickle`的模块。 `pickle`模块允许您分别使用`load`和`dump`方法读取和写入数据。
149 |
150 | ## 写入二进制数据
151 |
152 | * * *
153 |
154 | ```py
155 | >> import pickle
156 | >>> f = open('pick.dat', 'wb')
157 | >>> pickle.dump(11, f)
158 | >>> pickle.dump("this is a line", f)
159 | >>> pickle.dump([1, 2, 3, 4], f)
160 | >>> f.close()
161 |
162 | ```
163 |
164 | ## 读取二进制数据
165 |
166 | * * *
167 |
168 | ```py
169 | >> import pickle
170 | >>> f = open('pick.dat', 'rb')
171 | >>> pickle.load(f)
172 | 11
173 | >>> pickle.load(f)
174 | "this is a line"
175 | >>> pickle.load(f)
176 | [1,2,3,4]
177 | >>> f.close()
178 |
179 | ```
180 |
181 | 如果没有更多数据要读取,则`pickle.load()`会引发`EOFError`或文件结尾错误。
182 |
183 | 在下一课中,我们将学习 python 中的[类和对象](/python-object-and-classes/)。
184 |
185 | * * *
186 |
187 | * * *
--------------------------------------------------------------------------------
/docs/19.md:
--------------------------------------------------------------------------------
1 | # Python 对象和类
2 |
3 | > 原文: [https://thepythonguru.com/python-object-and-classes/](https://thepythonguru.com/python-object-and-classes/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | ## 创建对象和类
12 |
13 | * * *
14 |
15 | Python 是一种面向对象的语言。 在 python 中,所有东西都是对象,即`int`,`str`,`bool`甚至模块,函数也是对象。
16 |
17 | 面向对象的编程使用对象来创建程序,这些对象存储数据和行为。
18 |
19 | ## 定义类
20 |
21 | * * *
22 |
23 | python 中的类名以`class`关键字开头,后跟冒号(`:`)。 类通常包含用于存储数据的数据字段和用于定义行为的方法。 python 中的每个类还包含一个称为*初始化器*的特殊方法(也称为构造器),该方法在每次创建新对象时自动被调用。
24 |
25 | 让我们来看一个例子。
26 |
27 | ```py
28 | class Person:
29 |
30 | # constructor or initializer
31 | def __init__(self, name):
32 | self.name = name # name is data field also commonly known as instance variables
33 |
34 | # method which returns a string
35 | def whoami(self):
36 | return "You are " + self.name
37 |
38 | ```
39 |
40 | 在这里,我们创建了一个名为`Person`的类,其中包含一个名为`name`和方法`whoami()`的数据字段。
41 |
42 | ## 什么是`self`?
43 |
44 | * * *
45 |
46 | python 中的所有方法(包括一些特殊方法,如初始化器)都具有第一个参数`self`。 此参数引用调用该方法的对象。 创建新对象时,会自动将`__init__`方法中的`self`参数设置为引用刚创建的对象。
47 |
48 | ## 从类创建对象
49 |
50 | * * *
51 |
52 | ```py
53 | p1 = Person('tom') # now we have created a new person object p1
54 | print(p1.whoami())
55 | print(p1.name)
56 |
57 | ```
58 |
59 | **预期输出**:
60 |
61 | ```py
62 | You are tom
63 | tom
64 |
65 | ```
66 |
67 | **注意**:
68 |
69 | 当您调用一个方法时,您无需将任何内容传递给`self`参数,python 就会在后台自动为您完成此操作。
70 |
71 | 您也可以更改`name`数据字段。
72 |
73 | ```py
74 | p1.name = 'jerry'
75 | print(p1.name)
76 |
77 | ```
78 |
79 | **预期输出**:
80 |
81 | ```py
82 | jerry
83 |
84 | ```
85 |
86 | 尽管在类之外授予对您的数据字段的访问权是一种不好的做法。 接下来,我们将讨论如何防止这种情况。
87 |
88 | ## 隐藏数据字段
89 |
90 | * * *
91 |
92 | 要隐藏数据字段,您需要定义私有数据字段。 在 python 中,您可以使用两个前划线来创建私有数据字段。 您还可以使用两个下划线定义私有方法。
93 |
94 | 让我们看一个例子
95 |
96 | ```py
97 | class BankAccount:
98 |
99 | # constructor or initializer
100 | def __init__(self, name, money):
101 | self.__name = name
102 | self.__balance = money # __balance is private now, so it is only accessible inside the class
103 |
104 | def deposit(self, money):
105 | self.__balance += money
106 |
107 | def withdraw(self, money):
108 | if self.__balance > money :
109 | self.__balance -= money
110 | return money
111 | else:
112 | return "Insufficient funds"
113 |
114 | def checkbalance(self):
115 | return self.__balance
116 |
117 | b1 = BankAccount('tim', 400)
118 | print(b1.withdraw(500))
119 | b1.deposit(500)
120 | print(b1.checkbalance())
121 | print(b1.withdraw(800))
122 | print(b1.checkbalance())
123 |
124 | ```
125 |
126 | **预期输出**:
127 |
128 | ```py
129 | Insufficient funds
130 | 900
131 | 800
132 | 100
133 |
134 | ```
135 |
136 | 让我们尝试访问类外部的`__balance`数据字段。
137 |
138 | ```py
139 | print(b1.__balance)
140 |
141 | ```
142 |
143 | **预期输出**:
144 |
145 | ```py
146 | AttributeError: 'BankAccount' object has no attribute '__balance'
147 |
148 | ```
149 |
150 | 如您所见,现在在类外部无法访问`__balance`字段。
151 |
152 | 在下一章中,我们将学习[运算符重载](/python-operator-overloading/)。
153 |
154 | * * *
155 |
156 | * * *
--------------------------------------------------------------------------------
/docs/2.md:
--------------------------------------------------------------------------------
1 | # 初级 Python
--------------------------------------------------------------------------------
/docs/20.md:
--------------------------------------------------------------------------------
1 | # Python 运算符重载
2 |
3 | > 原文: [https://thepythonguru.com/python-operator-overloading/](https://thepythonguru.com/python-operator-overloading/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 您已经看到可以使用`+`运算符添加数字,并同时连接字符串。 这是可能的,因为`int`类和`str`类都重载了`+`运算符。 运算符实际上是在各个类中定义的方法。 运算符的定义方法称为运算符重载。 例如:要对自定义对象使用`+`运算符,您需要定义一个名为`__add__`的方法。
12 |
13 | 让我们举个例子来更好地理解
14 |
15 | ```py
16 | import math
17 |
18 | class Circle:
19 |
20 | def __init__(self, radius):
21 | self.__radius = radius
22 |
23 | def setRadius(self, radius):
24 | self.__radius = radius
25 |
26 | def getRadius(self):
27 | return self.__radius
28 |
29 | def area(self):
30 | return math.pi * self.__radius ** 2
31 |
32 | def __add__(self, another_circle):
33 | return Circle( self.__radius + another_circle.__radius )
34 |
35 | c1 = Circle(4)
36 | print(c1.getRadius())
37 |
38 | c2 = Circle(5)
39 | print(c2.getRadius())
40 |
41 | c3 = c1 + c2 # This became possible because we have overloaded + operator by adding a method named __add__
42 | print(c3.getRadius())
43 |
44 | ```
45 |
46 | **预期输出**:
47 |
48 | ```py
49 | 4
50 | 5
51 | 9
52 |
53 | ```
54 |
55 | ```py
56 | import math
57 |
58 | class Circle:
59 |
60 | def __init__(self, radius):
61 | self.__radius = radius
62 |
63 | def setRadius(self, radius):
64 | self.__radius = radius
65 |
66 | def getRadius(self):
67 | return self.__radius
68 |
69 | def area(self):
70 | return math.pi * self.__radius ** 2
71 |
72 | def __add__(self, another_circle):
73 | return Circle( self.__radius + another_circle.__radius )
74 |
75 | c1 = Circle(4)
76 | print(c1.getRadius())
77 |
78 | c2 = Circle(5)
79 | print(c2.getRadius())
80 |
81 | c3 = c1 + c2 # This became possible because we have overloaded + operator by adding a method named __add__
82 | print(c3.getRadius())
83 | ```
84 |
85 | 在上面的示例中,我们添加了`__add__()`方法,该方法允许使用`+`运算符添加两个圆形对象。 在`__add__()`方法内部,我们正在创建一个新对象并将其返回给调用者。
86 |
87 | Python 还有许多其他特殊方法,例如`__add__()`,请参见下面的列表。
88 |
89 | | 运算符 | 函数 | 方法说明 |
90 | | --- | --- | --- |
91 | | `+` | `__add__(self, other)` | 加法 |
92 | | `*` | `__mul__(self, other)` | 乘法 |
93 | | `-` | `__sub__(self, other)` | 减法 |
94 | | `%` | `__mod__(self, other)` | 余数 |
95 | | `/` | `__truediv__(self, other)` | 除法 |
96 | | `<` | `__lt__(self, other)` | 小于 |
97 | | `<=` | `__le__(self, other)` | 小于或等于 |
98 | | `==` | `__eq__(self, other)` | 等于 |
99 | | `!=` | `__ne__(self, other)` | 不等于 |
100 | | `>` | `__gt__(self, other)` | 大于 |
101 |
102 | `>=`,`__ge__(self, other)`,大于或等于`[index]`,`__getitem__(self, index)`,索引运算符`in`,`__contains__(self, value)`,检查成员资格`len`,`__len__(self)`,元素数`str`,`__str__(self)`的字符串表示形式
103 |
104 | 下面的程序使用上面提到的一些函数来重载运算符。
105 |
106 | ```py
107 | import math
108 |
109 | class Circle:
110 |
111 | def __init__(self, radius):
112 | self.__radius = radius
113 |
114 | def setRadius(self, radius):
115 | self.__radius = radius
116 |
117 | def getRadius(self):
118 | return self.__radius
119 |
120 | def area(self):
121 | return math.pi * self.__radius ** 2
122 |
123 | def __add__(self, another_circle):
124 | return Circle( self.__radius + another_circle.__radius )
125 |
126 | def __gt__(self, another_circle):
127 | return self.__radius > another_circle.__radius
128 |
129 | def __lt__(self, another_circle):
130 | return self.__radius < another_circle.__radius
131 |
132 | def __str__(self):
133 | return "Circle with radius " + str(self.__radius)
134 |
135 | c1 = Circle(4)
136 | print(c1.getRadius())
137 |
138 | c2 = Circle(5)
139 | print(c2.getRadius())
140 |
141 | c3 = c1 + c2
142 | print(c3.getRadius())
143 |
144 | print( c3 > c2) # Became possible because we have added __gt__ method
145 |
146 | print( c1 < c2) # Became possible because we have added __lt__ method
147 |
148 | print(c3) # Became possible because we have added __str__ method
149 |
150 | ```
151 |
152 | **预期输出**:
153 |
154 | ```py
155 | 4
156 | 5
157 | 9
158 | True
159 | True
160 | Circle with radius 9
161 |
162 | ```
163 |
164 | ```py
165 | import math
166 |
167 | class Circle:
168 |
169 | def __init__(self, radius):
170 | self.__radius = radius
171 |
172 | def setRadius(self, radius):
173 | self.__radius = radius
174 |
175 | def getRadius(self):
176 | return self.__radius
177 |
178 | def area(self):
179 | return math.pi * self.__radius ** 2
180 |
181 | def __add__(self, another_circle):
182 | return Circle( self.__radius + another_circle.__radius )
183 |
184 | def __gt__(self, another_circle):
185 | return self.__radius > another_circle.__radius
186 |
187 | def __lt__(self, another_circle):
188 | return self.__radius < another_circle.__radius
189 |
190 | def __str__(self):
191 | return "Circle with radius " + str(self.__radius)
192 |
193 | c1 = Circle(4)
194 | print(c1.getRadius())
195 |
196 | c2 = Circle(5)
197 | print(c2.getRadius())
198 |
199 | c3 = c1 + c2
200 | print(c3.getRadius())
201 |
202 | print( c3 > c2) # Became possible because we have added __gt__ method
203 |
204 | print( c1 < c2) # Became possible because we have added __lt__ method
205 |
206 | print(c3) # Became possible because we have added __str__ method
207 | ```
208 |
209 | 下一课是[继承和多态](/python-inheritance-and-polymorphism/)。
210 |
211 | * * *
212 |
213 | * * *
--------------------------------------------------------------------------------
/docs/21.md:
--------------------------------------------------------------------------------
1 | # Python 继承与多态
2 |
3 | > 原文: [https://thepythonguru.com/python-inheritance-and-polymorphism/](https://thepythonguru.com/python-inheritance-and-polymorphism/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 继承允许程序员首先创建一个通用类,然后再将其扩展为更专业的类。 它还允许程序员编写更好的代码。
12 |
13 | 使用继承,您可以继承所有访问数据字段和方法,还可以添加自己的方法和字段,因此继承提供了一种组织代码的方法,而不是从头开始重写代码。
14 |
15 | 在面向对象的术语中,当`X`类扩展了`Y`类时,则`Y`被称为*超类*或*基类*,而`X`被称为*子类或派生类*。 还有一点要注意,子类只能访问非私有的数据字段和方法,私有数据字段和方法只能在该类内部访问。
16 |
17 | 创建子类的语法是:
18 |
19 | ```py
20 | class SubClass(SuperClass):
21 | # data fields
22 | # instance methods
23 |
24 | ```
25 |
26 | 让我们以一个例子来说明这一点。
27 |
28 | ```py
29 | class Vehicle:
30 |
31 | def __init__(self, name, color):
32 | self.__name = name # __name is private to Vehicle class
33 | self.__color = color
34 |
35 | def getColor(self): # getColor() function is accessible to class Car
36 | return self.__color
37 |
38 | def setColor(self, color): # setColor is accessible outside the class
39 | self.__color = color
40 |
41 | def getName(self): # getName() is accessible outside the class
42 | return self.__name
43 |
44 | class Car(Vehicle):
45 |
46 | def __init__(self, name, color, model):
47 | # call parent constructor to set name and color
48 | super().__init__(name, color)
49 | self.__model = model
50 |
51 | def getDescription(self):
52 | return self.getName() + self.__model + " in " + self.getColor() + " color"
53 |
54 | # in method getDescrition we are able to call getName(), getColor() because they are
55 | # accessible to child class through inheritance
56 |
57 | c = Car("Ford Mustang", "red", "GT350")
58 | print(c.getDescription())
59 | print(c.getName()) # car has no method getName() but it is accessible through class Vehicle
60 |
61 | ```
62 |
63 | **预期输出**:
64 |
65 | ```py
66 | Ford MustangGT350 in red color
67 | Ford Mustang
68 |
69 | ```
70 |
71 | 在这里,我们创建了基类`Vehicle`及其子类`Car`。 注意,我们没有在`Car`类中定义`getName()`,但是我们仍然可以访问它,因为类`Car`从`Vehicle`类继承。 在上面的代码中,`super()`方法用于调用基类的方法。 这是`super()`的工作方式
72 |
73 | 假设您需要在子类的基类中调用名为`get_information()`的方法,则可以使用以下代码进行调用。
74 |
75 | ```py
76 | super().get_information()
77 |
78 | ```
79 |
80 | 同样,您可以使用以下代码从子类构造器中调用基类构造器。
81 |
82 | ```py
83 | super().__init__()
84 |
85 | ```
86 |
87 | ## 多重继承
88 |
89 | * * *
90 |
91 | 与 Java 和 C# 等语言不同,python 允许多重继承,即您可以同时从多个类继承,
92 |
93 | ```py
94 | class Subclass(SuperClass1, SuperClass2, ...):
95 | # initializer
96 | # methods
97 |
98 | ```
99 |
100 | 让我们举个例子:
101 |
102 | ```py
103 | class MySuperClass1():
104 |
105 | def method_super1(self):
106 | print("method_super1 method called")
107 |
108 | class MySuperClass2():
109 |
110 | def method_super2(self):
111 | print("method_super2 method called")
112 |
113 | class ChildClass(MySuperClass1, MySuperClass2):
114 |
115 | def child_method(self):
116 | print("child method")
117 |
118 | c = ChildClass()
119 | c.method_super1()
120 | c.method_super2()
121 |
122 | ```
123 |
124 | **预期输出**:
125 |
126 | ```py
127 | method_super1 method called
128 | method_super2 method called
129 |
130 | ```
131 |
132 | 如您所见,因为`ChildClass`继承了`MySuperClass1`,`MySuperClass2`,所以`ChildClass`的对象现在可以访问`method_super1()`和`method_super2()`。
133 |
134 | ## 覆盖方法
135 |
136 | * * *
137 |
138 | 要覆盖基类中的方法,子类需要定义一个具有相同签名的方法。 (即与基类中的方法相同的方法名称和相同数量的参数)。
139 |
140 | ```py
141 | class A():
142 |
143 | def __init__(self):
144 | self.__x = 1
145 |
146 | def m1(self):
147 | print("m1 from A")
148 |
149 | class B(A):
150 |
151 | def __init__(self):
152 | self.__y = 1
153 |
154 | def m1(self):
155 | print("m1 from B")
156 |
157 | c = B()
158 | c.m1()
159 |
160 | ```
161 |
162 | **预期输出**:
163 |
164 | ```py
165 | m1 from B
166 |
167 | ```
168 |
169 | 在这里,我们从基类中重写`m1()`方法。 尝试在`B`类中注释`m1()`方法,现在将运行`Base`类中的`m1()`方法,即`A`类。
170 |
171 | **预期输出**:
172 |
173 | ```py
174 | m1 from A
175 |
176 | ```
177 |
178 | ## `isinstance()`函数
179 |
180 | * * *
181 |
182 | `isinstance()`函数用于确定对象是否为该类的实例。
183 |
184 | **语法**: `isinstance(object, class_type)`
185 |
186 | ```py
187 | >>> isinstance(1, int)
188 | True
189 |
190 | >>> isinstance(1.2, int)
191 | False
192 |
193 | >>> isinstance([1,2,3,4], list)
194 | True
195 |
196 | ```
197 |
198 | 下一章[异常处理](/python-exception-handling/)。
199 |
200 | * * *
201 |
202 | * * *
--------------------------------------------------------------------------------
/docs/22.md:
--------------------------------------------------------------------------------
1 | # Python 异常处理
2 |
3 | > 原文: [https://thepythonguru.com/python-exception-handling/](https://thepythonguru.com/python-exception-handling/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 异常处理使您能够优雅地处理错误并对其进行有意义的处理。 如果未找到所需文件,则向用户显示一条消息。 Python 使用`try`和`except`块处理异常。
12 |
13 | **语法**:
14 |
15 | ```py
16 | try:
17 | # write some code
18 | # that might throw exception
19 | except :
20 | # Exception handler, alert the user
21 |
22 | ```
23 |
24 | 如您在`try`块中看到的那样,您需要编写可能引发异常的代码。 当发生异常时,将跳过`try`块中的代码。 如果`except`子句中存在匹配的异常类型,则执行其处理器。
25 |
26 | 让我们举个例子:
27 |
28 | ```py
29 | try:
30 | f = open('somefile.txt', 'r')
31 | print(f.read())
32 | f.close()
33 | except IOError:
34 | print('file not found')
35 |
36 | ```
37 |
38 | 上面的代码如下:
39 |
40 | 1. 执行`try`和`except`块之间的第一条语句。
41 | 2. 如果没有异常发生,则将跳过`except`子句下的代码。
42 | 3. 如果文件不存在,则会引发异常,并且`try`块中的其余代码将被跳过
43 | 4. 发生异常时,如果异常类型与`except`关键字后的异常名称匹配,则将执行该`except`子句中的代码。
44 |
45 | **注意**:
46 |
47 | 上面的代码仅能处理`IOError`异常。 要处理其他类型的异常,您需要添加更多的`except`子句。
48 |
49 | `try`语句可以具有多个`except`子句,也可以具有可选的`else`和/或`finally`语句。
50 |
51 | ```py
52 | try:
53 |
54 | except :
55 |
56 | except :
57 |
58 | except:
59 |
60 | else:
61 |
62 | finally:
63 |
64 |
65 | ```
66 |
67 | `except`子句类似于`elif`。 发生异常时,将检查该异常以匹配`except`子句中的异常类型。 如果找到匹配项,则执行匹配大小写的处理器。 另请注意,在最后的`except`子句中,`ExceptionType`被省略。 如果异常不匹配最后一个`except`子句之前的任何异常类型,则执行最后一个`except`子句的处理器。
68 |
69 | **注意**:
70 |
71 | `else`子句下的语句仅在没有引发异常时运行。
72 |
73 | **注意**:
74 |
75 | 无论是否发生异常,`finally`子句中的语句都将运行。
76 |
77 | 现在举个例子。
78 |
79 | ```py
80 | try:
81 | num1, num2 = eval(input("Enter two numbers, separated by a comma : "))
82 | result = num1 / num2
83 | print("Result is", result)
84 |
85 | except ZeroDivisionError:
86 | print("Division by zero is error !!")
87 |
88 | except SyntaxError:
89 | print("Comma is missing. Enter numbers separated by comma like this 1, 2")
90 |
91 | except:
92 | print("Wrong input")
93 |
94 | else:
95 | print("No exceptions")
96 |
97 | finally:
98 | print("This will execute no matter what")
99 |
100 | ```
101 |
102 | **注意**:
103 |
104 | `eval()`函数允许 python 程序在其内部运行 python 代码,`eval()`需要一个字符串参数。
105 |
106 | 要了解有关`eval()`的更多信息,请访问 Python 中的[`eval()`](/python-builtin-functions/eval/)。
107 |
108 | ## 引发异常
109 |
110 | * * *
111 |
112 | 要从您自己的方法引发异常,您需要像这样使用`raise`关键字
113 |
114 | ```py
115 | raise ExceptionClass("Your argument")
116 |
117 | ```
118 |
119 | 让我们举个例子
120 |
121 | ```py
122 | def enterage(age):
123 | if age < 0:
124 | raise ValueError("Only positive integers are allowed")
125 |
126 | if age % 2 == 0:
127 | print("age is even")
128 | else:
129 | print("age is odd")
130 |
131 | try:
132 | num = int(input("Enter your age: "))
133 | enterage(num)
134 |
135 | except ValueError:
136 | print("Only positive integers are allowed")
137 | except:
138 | print("something is wrong")
139 |
140 | ```
141 |
142 | 运行程序并输入正整数。
143 |
144 | **预期输出**:
145 |
146 | ```py
147 | Enter your age: 12
148 | age is even
149 |
150 | ```
151 |
152 | 再次运行该程序并输入一个负数。
153 |
154 | **预期输出**:
155 |
156 | ```py
157 | Enter your age: -12
158 | Only integers are allowed
159 |
160 | ```
161 |
162 | ## 使用异常对象
163 |
164 | * * *
165 |
166 | 现在您知道如何处理异常,在本节中,我们将学习如何在异常处理器代码中访问异常对象。 您可以使用以下代码将异常对象分配给变量。
167 |
168 | ```py
169 | try:
170 | # this code is expected to throw exception
171 | except ExceptionType as ex:
172 | # code to handle exception
173 |
174 | ```
175 |
176 | 如您所见,您可以将异常对象存储在变量`ex`中。 现在,您可以在异常处理器代码中使用此对象。
177 |
178 | ```py
179 | try:
180 | number = eval(input("Enter a number: "))
181 | print("The number entered is", number)
182 | except NameError as ex:
183 | print("Exception:", ex)
184 |
185 | ```
186 |
187 | 运行程序并输入一个数字。
188 |
189 | **预期输出**:
190 |
191 | ```py
192 | Enter a number: 34
193 | The number entered is 34
194 |
195 | ```
196 |
197 | 再次运行程序并输入一个字符串。
198 |
199 | **预期输出**:
200 |
201 | ```py
202 | Enter a number: one
203 | Exception: name 'one' is not defined
204 |
205 | ```
206 |
207 | ## 创建自定义异常类
208 |
209 | * * *
210 |
211 | 您可以通过扩展`BaseException`类或`BaseException`的子类来创建自定义异常类。
212 |
213 | 
214 |
215 | 如您所见,python 中的大多数异常类都是从`BaseException`类扩展而来的。 您可以从`BaseException`类或`BaseException`的子类(例如`RuntimeError`)派生自己的异常类。
216 |
217 | 创建一个名为`NegativeAgeException.py`的新文件,并编写以下代码。
218 |
219 | ```py
220 | class NegativeAgeException(RuntimeError):
221 | def __init__(self, age):
222 | super().__init__()
223 | self.age = age
224 |
225 | ```
226 |
227 | 上面的代码创建了一个名为`NegativeAgeException`的新异常类,该异常类仅由使用`super().__init__()`调用父类构造器并设置`age`的构造器组成。
228 |
229 | ## 使用自定义异常类
230 |
231 | * * *
232 |
233 | ```py
234 | def enterage(age):
235 | if age < 0:
236 | raise NegativeAgeException("Only positive integers are allowed")
237 |
238 | if age % 2 == 0:
239 | print("age is even")
240 | else:
241 | print("age is odd")
242 |
243 | try:
244 | num = int(input("Enter your age: "))
245 | enterage(num)
246 | except NegativeAgeException:
247 | print("Only positive integers are allowed")
248 | except:
249 | print("something is wrong")
250 |
251 | ```
252 |
253 | 在下一篇文章中,我们将学习 [Python 模块](/python-modules/)。
254 |
255 | * * *
256 |
257 | * * *
--------------------------------------------------------------------------------
/docs/23.md:
--------------------------------------------------------------------------------
1 | # Python 模块
2 |
3 | > 原文: [https://thepythonguru.com/python-modules/](https://thepythonguru.com/python-modules/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | Python 模块是一个普通的 python 文件,可以存储函数,变量,类,常量等。模块帮助我们组织相关代码。 例如,python 中的`math`模块具有与数学相关的函数。
12 |
13 | ## 创建模块
14 |
15 | * * *
16 |
17 | 创建一个名为`mymodule.py`的新文件并编写以下代码。
18 |
19 | ```py
20 | foo = 100
21 |
22 | def hello():
23 | print("i am from mymodule.py")
24 |
25 | ```
26 |
27 | 如您所见,我们在模块中定义了全局变量`foo`和函数`hello()`。 现在要在程序中使用此模块,我们首先需要使用`import`语句将其导入
28 |
29 | ```py
30 | import mymodule
31 |
32 | ```
33 |
34 | 现在您可以使用以下代码在`mymodule.py`中使用变量和调用函数。
35 |
36 | ```py
37 | import mymodule
38 |
39 | print(mymodule.foo)
40 | print(mymodule.hello())
41 |
42 | ```
43 |
44 | **预期输出**:
45 |
46 | ```py
47 | 100
48 | i am from mymodule.py
49 |
50 | ```
51 |
52 | 请记住,您需要先指定模块名称才能访问其变量和函数,否则将导致错误。
53 |
54 | ## 结合使用`from`和`import`
55 |
56 | * * *
57 |
58 | 使用`import`语句会导入模块中的所有内容,如果只想访问特定的函数或变量该怎么办? 这是`from`语句的来源,这里是如何使用它。
59 |
60 | ```py
61 | from mymodule import foo # this statement import only foo variable from mymodule
62 | print(foo)
63 |
64 | ```
65 |
66 | **预期输出**:
67 |
68 | ```py
69 | 100
70 |
71 | ```
72 |
73 | **注意**:
74 |
75 | 在这种情况下,您无需指定模块名称即可访问变量和函数。
76 |
77 | ## `dir()`方法
78 |
79 | * * *
80 |
81 | `dir()`是一种内置方法,用于查找对象的所有属性(即所有可用的类,函数,变量和常量)。 正如我们已经在 python 中讨论的所有对象一样,我们可以使用`dir()`方法来查找模块的属性,如下所示:
82 |
83 | ```py
84 | dir(module_name)
85 |
86 | ```
87 |
88 | `dir()`返回包含可用属性名称的字符串列表。
89 |
90 | ```py
91 | >>> dir(mymodule)
92 | ['__builtins__', '__cached__', '__doc__', '__file__',
93 | '__loader__', '__name__', '__package__', '__spec__', 'foo', 'hello']
94 |
95 | ```
96 |
97 | 如您所见,除了`foo`和`hello`之外,`mymodule`中还有其他属性。 这些是 python 自动提供给所有模块的内置属性。
98 |
99 | 恭喜您已经完成了掌握 Python 所需的所有构建基块!!
100 |
101 | * * *
102 |
103 | * * *
--------------------------------------------------------------------------------
/docs/24.md:
--------------------------------------------------------------------------------
1 | # 高级 Python
--------------------------------------------------------------------------------
/docs/25.md:
--------------------------------------------------------------------------------
1 | # Python `*args`和`**kwargs`
2 |
3 | > 原文: [https://thepythonguru.com/python-args-and-kwargs/](https://thepythonguru.com/python-args-and-kwargs/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 什么是`*args`?
12 |
13 | `*args`允许我们将可变数量的参数传递给函数。 让我们以一个例子来阐明这一点。
14 |
15 | 假设您创建了一个将两个数字相加的函数。
16 |
17 | ```py
18 | def sum(a, b):
19 | print("sum is", a+b)
20 |
21 | ```
22 |
23 | 如您所见,该程序仅接受两个数字,如果您要传递两个以上的参数,这就是`*args`起作用的地方。
24 |
25 | ```py
26 | def sum(*args):
27 | s = 0
28 | for i in args:
29 | s += i
30 | print("sum is", s)
31 |
32 | ```
33 |
34 | 现在,您可以像这样将任意数量的参数传递给函数,
35 |
36 | ```py
37 | >>> sum(1, 2, 3)
38 | 6
39 | >>> sum(1, 2, 3, 4, 5, 7)
40 | 22
41 | >>> sum(1, 2, 3, 4, 5, 7, 8, 9, 10)
42 | 49
43 | >>> sum()
44 | 0
45 |
46 | ```
47 |
48 | **注意**:
49 |
50 | `*args`的名称只是一个约定,您可以使用任何有效标识符。 例如`*myargs`是完全有效的。
51 |
52 | ## 什么是`**kwargs`?
53 |
54 | * * *
55 |
56 | `**kwargs`允许我们传递可变数量的关键字参数,例如`func_name(name='tim', team='school')`
57 |
58 | ```py
59 | def my_func(**kwargs):
60 | for i, j in kwargs.items():
61 | print(i, j)
62 |
63 | my_func(name='tim', sport='football', roll=19)
64 |
65 | ```
66 |
67 | **预期输出**:
68 |
69 | ```py
70 | sport football
71 | roll 19
72 | name tim
73 |
74 | ```
75 |
76 | ## 在函数调用中使用`*args`和`**kwargs`
77 |
78 | * * *
79 |
80 | 您可以使用`*args`将可迭代变量中的元素传递给函数。 以下示例将清除所有内容。
81 |
82 | ```py
83 | def my_three(a, b, c):
84 | print(a, b, c)
85 |
86 | a = [1,2,3]
87 | my_three(*a) # here list is broken into three elements
88 |
89 | ```
90 |
91 | **注意**:
92 |
93 | 仅当参数数量与可迭代变量中的元素数量相同时,此方法才有效。
94 |
95 | 同样,您可以使用`**kwargs`来调用如下函数:
96 |
97 | ```py
98 | def my_three(a, b, c):
99 | print(a, b, c)
100 |
101 | a = {'a': "one", 'b': "two", 'c': "three" }
102 | my_three(**a)
103 |
104 | ```
105 |
106 | 请注意,要使此工作有效,需要做两件事:
107 |
108 | 1. 函数中的参数名称必须与字典中的键名称匹配。
109 | 2. 参数的数量应与字典中的键的数量相同。
110 |
111 | * * *
112 |
113 | * * *
--------------------------------------------------------------------------------
/docs/26.md:
--------------------------------------------------------------------------------
1 | # Python 生成器
2 |
3 | > 原文: [https://thepythonguru.com/python-generators/](https://thepythonguru.com/python-generators/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 生成器是用于创建迭代器的函数,因此可以在`for`循环中使用它。
12 |
13 | ## 创建生成器
14 |
15 | * * *
16 |
17 | 生成器的定义类似于函数,但只有一个区别,我们使用`yield`关键字返回用于`for`循环的每次迭代的值。 让我们看一个示例,其中我们试图克隆 python 的内置`range()`函数。
18 |
19 | ```py
20 | def my_range(start, stop, step = 1):
21 | if stop <= start:
22 | raise RuntimeError("start must be smaller than stop")
23 | i = start
24 | while i < stop:
25 | yield i
26 | i += step
27 |
28 | try:
29 | for k in my_range(10, 50, 3):
30 | print(k)
31 | except RuntimeError as ex:
32 | print(ex)
33 | except:
34 | print("Unknown error occurred")
35 |
36 | ```
37 |
38 | **预期输出**:
39 |
40 | ```py
41 | 10
42 | 13
43 | 16
44 | 19
45 | 22
46 | 25
47 | 28
48 | 31
49 | 34
50 | 37
51 | 40
52 | 43
53 | 46
54 | 49
55 |
56 | ```
57 |
58 | ```py
59 | def my_range(start, stop, step = 1):
60 | if stop <= start:
61 | raise RuntimeError("start must be smaller than stop")
62 | i = start
63 | while i < stop:
64 | yield i
65 | i += step
66 |
67 | try:
68 | for k in my_range(10, 50, 3):
69 | print(k)
70 | except RuntimeError as ex:
71 | print(ex)
72 | except:
73 | print("Unknown error occurred")
74 | ```
75 |
76 | `my_range()`的工作方式如下:
77 |
78 | 在`for`循环中,调用`my_range()`函数,它将初始化三个参数(`start`,`stop`和`step`)的值,并检查`stop`是否小于或等于`start`。 `i`被分配了`start`的值。 此时,`i`为`10`,因此`while`条件的值为`True`,而`while`循环开始执行。 在下一个语句`yield`中,将控制转移到`for`循环,并将`i`的当前值分配给变量`k`,在`for`循环打印语句中执行该语句,然后该控件再次传递到函数`my_range()`内的第 7 行 `i`递增。 此过程一直重复进行,直到`i < stop`为止。
79 |
80 | * * *
81 |
82 | * * *
--------------------------------------------------------------------------------
/docs/27.md:
--------------------------------------------------------------------------------
1 | # Python 正则表达式
2 |
3 | > 原文: [https://thepythonguru.com/python-regular-expression/](https://thepythonguru.com/python-regular-expression/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 正则表达式广泛用于模式匹配。 Python 具有对常规功能的内置支持。 要使用正则表达式,您需要导入`re`模块。
12 |
13 | ```py
14 | import re
15 |
16 | ```
17 |
18 | 现在您可以使用正则表达式了。
19 |
20 | ## `search`方法
21 |
22 | * * *
23 |
24 | `re.search()`用于查找字符串中模式的第一个匹配项。
25 |
26 | **语法**: `re.search(pattern, string, flags[optional])`
27 |
28 | `re.search()`方法接受模式和字符串,并在成功时返回`match`对象;如果找不到匹配项,则返回`None`。 `match`对象具有`group()`方法,该方法在字符串中包含匹配的文本。
29 |
30 | 您必须使用原始字符串来指定模式,即像这样用`r`开头的字符串。
31 |
32 | ```py
33 | r'this \n'
34 |
35 | ```
36 |
37 | 所有特殊字符和转义序列在原始字符串中均失去其特殊含义,因此`\n`不是换行符,它只是一个反斜杠`\`后跟一个`n`。
38 |
39 | ```py
40 | >>> import re
41 | >>> s = "my number is 123"
42 | >>> match = re.search(r'\d\d\d', s)
43 | >>> match
44 | <_sre.SRE_Match object; span=(13, 16), match='123'>
45 | >>> match.group()
46 | '123'
47 |
48 | ```
49 |
50 | 上面我们使用`\d\d\d`作为模式。 `\d`正则表达式匹配一位数字,因此
51 |
52 | `\d\d\d`将匹配`111`,`222`和`786`之类的数字。 它与`12`和`1444`不匹配。
53 |
54 | ## 正则表达式中使用的基本模式
55 |
56 | * * *
57 |
58 | | 符号 | 描述 |
59 | | --- | --- |
60 | | `.` | 点匹配除换行符以外的任何字符 |
61 | | `\w` | 匹配任何单词字符,即字母,字母数字,数字和下划线(`_`) |
62 | | `\W` | 匹配非单词字符 |
63 | | `\d` | 匹配一个数字 |
64 | | `\D` | 匹配不是数字的单个字符 |
65 | | `\s` | 匹配任何空白字符,例如`\n`,`\t`,空格 |
66 | | `\S` | 匹配单个非空白字符 |
67 | | `[abc]` | 匹配集合中的单个字符,即匹配`a`,`b`或`c` |
68 | | `[^abc]` | 匹配`a`,`b`和`c`以外的单个字符 |
69 | | `[a-z]` | 匹配`a`至`z`范围内的单个字符。 |
70 | | `[a-zA-Z]` | 匹配`a-z`或`A-Z`范围内的单个字符 |
71 | | `[0-9]` | 匹配`0`-`9`范围内的单个字符 |
72 | | `^` | 匹配从字符串开头开始 |
73 | | `$` | 匹配从字符串末尾开始 |
74 | | `+` | 匹配一个或多个前面的字符(贪婪匹配)。 |
75 | | `*` | 匹配零个或多个前一个字符(贪婪匹配)。 |
76 |
77 | 再举一个例子:
78 |
79 | ```py
80 | import re
81 | s = "tim email is tim@somehost.com"
82 | match = re.search(r'[\w.-]+@[\w.-]+', s)
83 |
84 | # the above regular expression will match a email address
85 |
86 | if match:
87 | print(match.group())
88 | else:
89 | print("match not found")
90 |
91 | ```
92 |
93 | 这里我们使用了`[\w.-]+@[\w.-]+`模式来匹配电子邮件地址。 成功后,`re.search()`返回一个`match`对象,其`group()`方法将包含匹配的文本。
94 |
95 | ## 捕捉组
96 |
97 | * * *
98 |
99 | 组捕获允许从匹配的字符串中提取部分。 您可以使用括号`()`创建组。 假设在上面的示例中,我们想从电子邮件地址中提取用户名和主机名。 为此,我们需要在用户名和主机名周围添加`()`,如下所示。
100 |
101 | ```py
102 | match = re.search(r'([\w.-]+)@([\w.-]+)', s)
103 |
104 | ```
105 |
106 | 请注意,括号不会更改模式匹配的内容。 如果匹配成功,则`match.group(1)`将包含第一个括号中的匹配,`match.group(2)`将包含第二个括号中的匹配。
107 |
108 | ```py
109 | import re
110 | s = "tim email is tim@somehost.com"
111 | match = re.search('([\w.-]+)@([\w.-]+)', s)
112 | if match:
113 | print(match.group()) ## tim@somehost.com (the whole match)
114 | print(match.group(1)) ## tim (the username, group 1)
115 | print(match.group(2)) ## somehost (the host, group 2)
116 |
117 | ```
118 |
119 | ## `findall()`函数
120 |
121 | * * *
122 |
123 | 如您所知,现在`re.search()`仅找到模式的第一个匹配项,如果我们想找到字符串中的所有匹配项,这就是`findall()`发挥作用的地方。
124 |
125 | **语法**: `findall(pattern, string, flags=0[optional])`
126 |
127 | 成功时,它将所有匹配项作为字符串列表返回,否则返回空列表。
128 |
129 | ```py
130 | import re
131 | s = "Tim's phone numbers are 12345-41521 and 78963-85214"
132 | match = re.findall(r'\d{5}', s)
133 |
134 | if match:
135 | print(match)
136 |
137 | ```
138 |
139 | **预期输出**:
140 |
141 | ```py
142 | ['12345', '41521', '78963', '85214']
143 |
144 | ```
145 |
146 | 您还可以通过`findall()`使用组捕获,当应用组捕获时,`findall()`返回一个元组列表,其中元组将包含匹配的组。 一个示例将清除所有内容。
147 |
148 | ```py
149 | import re
150 | s = "Tim's phone numbers are 12345-41521 and 78963-85214"
151 | match = re.findall(r'(\d{5})-(\d{5})', s)
152 | print(match)
153 |
154 | for i in match:
155 | print()
156 | print(i)
157 | print("First group", i[0])
158 | print("Second group", i[1])
159 |
160 | ```
161 |
162 | **预期输出**:
163 |
164 | ```py
165 | [('12345', '41521'), ('78963', '85214')]
166 |
167 | ('12345', '41521')
168 | First group 12345
169 | Second group 41521
170 |
171 | ('78963', '85214')
172 | First group 78963
173 | Second group 85214
174 |
175 | ```
176 |
177 | ## 可选标志
178 |
179 | * * *
180 |
181 | `re.search()`和`re.findall()`都接受可选参数称为标志。 标志用于修改模式匹配的行为。
182 |
183 | | 标志 | 描述 |
184 | | --- | --- |
185 | | `re.IGNORECASE` | 忽略大写和小写 |
186 | | `re.DOTALL` | 允许(`.`)匹配换行符,默认(`.`)匹配除换行符之外的任何字符 |
187 | | `re.MULTILINE` | 这将允许`^`和`$`匹配每行的开始和结束 |
188 |
189 | ## 使用`re.match()`
190 |
191 | * * *
192 |
193 | `re.match()`与`re.search()`非常相似,区别在于它将在字符串的开头开始寻找匹配项。
194 |
195 | ```py
196 | import re
197 | s = "python tuts"
198 | match = re.match(r'py', s)
199 | if match:
200 | print(match.group())
201 |
202 | ```
203 |
204 | 您可以通过使用`re.search()`将`^`应用于模式来完成同一件事。
205 |
206 | ```py
207 | import re
208 | s = "python tuts"
209 | match = re.search(r'^py', s)
210 | if match:
211 | print(match.group())
212 |
213 | ```
214 |
215 | 这样就完成了您需要了解的有关`re`模块的所有内容。
216 |
217 | * * *
218 |
219 | * * *
--------------------------------------------------------------------------------
/docs/28.md:
--------------------------------------------------------------------------------
1 | # 使用 PIP 在 python 中安装包
2 |
3 | > 原文: [https://thepythonguru.com/installing-packages-in-python-using-pip](https://thepythonguru.com/installing-packages-in-python-using-pip)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | PIP 是一个包管理系统,用于从存储库安装包。 您可以使用`pip`安装 [http://pypi.python.org/pypi](http://pypi.python.org/pypi) 上可用的各种包。 PIP 与 php 中的作曲家非常相似。 PIP 是递归的首字母缩写,代表 PIP 安装包。
12 |
13 | ## 安装 PIP
14 |
15 | * * *
16 |
17 | Python 2.7.9 及更高版本(python2 系列)和 Python 3.4 及更高版本(python 3 系列)已经带有 pip。
18 |
19 | 要检查您的 python 版本,您需要输入以下命令:
20 |
21 | ```py
22 | python -V
23 |
24 | ```
25 |
26 | 如果您的 python 版本不属于上述任何版本,则需要手动安装`pip`(请参见下面的链接)。
27 |
28 | * [单击此处以获取 Windows 安装说明](http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows)。
29 | * [单击此处以获取 Linux 指南](https://pip.pypa.io/en/latest/installing.html)。
30 |
31 | ## 安装包
32 |
33 | * * *
34 |
35 | 假设您要安装一个名为 [Requests](https://pypi.python.org/pypi/requests/2.7.0) 的包(用于发出 HTTP 请求)。 您需要发出以下命令。
36 |
37 | ```py
38 | pip install requests # this will install latest request package
39 | pip install requests==2.6.0 # this will install requests 2.6.0 package not the latest package
40 | pip install requests>=2.6.0 # specify a minimum version if it's not available pip will install the latest version
41 |
42 | ```
43 |
44 | **注意**:
45 |
46 | `pip.exe`存储在`C:\Python34\Scripts`下,因此您需要去那里安装包。 或者,将整个路径添加到`PATH`环境变量。 这样,您可以从任何目录访问`pip`。
47 |
48 | ## 卸载包
49 |
50 | * * *
51 |
52 | 要卸载包,请使用以下命令。
53 |
54 | ```py
55 | pip uninstall package_name
56 |
57 | ```
58 |
59 | ## 升级包
60 |
61 | * * *
62 |
63 | ```py
64 | pip install --upgrade package_name
65 |
66 | ```
67 |
68 | ## 搜索包
69 |
70 | * * *
71 |
72 | ```py
73 | pip search "your query"
74 |
75 | ```
76 |
77 | **注意**:
78 |
79 | 您无需在搜索字词前后添加引号。
80 |
81 | ## 列出已安装的包
82 |
83 | * * *
84 |
85 | ```py
86 | pip list
87 |
88 | ```
89 |
90 | 上面的命令将列出所有已安装的包。
91 |
92 | ## 列出过时的已安装包
93 |
94 | * * *
95 |
96 | ```py
97 | pip list --outdated
98 |
99 | ```
100 |
101 | ## 有关已安装包的详细信息
102 |
103 | * * *
104 |
105 | 您可以使用以下命令来获取有关已安装包的信息,即包名称,版本,位置,依赖项。
106 |
107 | ```py
108 | pip show package_name
109 |
110 | ```
111 |
112 | * * *
113 |
114 | * * *
--------------------------------------------------------------------------------
/docs/29.md:
--------------------------------------------------------------------------------
1 | # Python `virtualenv`指南
2 |
3 | > 原文: [https://thepythonguru.com/python-virtualenv-guide/](https://thepythonguru.com/python-virtualenv-guide/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | **注意**:
12 |
13 | 本教程需要`pip`,如果您尚未这样做,请首先通过[安装`pip`](/installing-packages-in-python-using-pip/)。
14 |
15 | `virtualenv`是用于分隔项目所需的不同依赖项的工具。 在处理多个项目时,一个项目需要一个与另一个项目完全不同的包版本是一个常见的问题,`virtualenv`可帮助我们解决此类问题。 它还有助于防止污染全局站点包。
16 |
17 | ## 安装`virtualenv`
18 |
19 | * * *
20 |
21 | `virtualenv`只是 [pypi](https://pypi.python.org/pypi/virtualenv/13.1.2) 提供的包,您可以使用`pip`安装`virtualenv`。
22 |
23 | ```py
24 | pip install virtualenv
25 |
26 | ```
27 |
28 | 安装后,您可能需要将`C:\Python34\Scripts`添加到`PATH`环境变量中。 这样,诸如`pip`,`virtualenv`之类的命令将在任何目录级别可用。
29 |
30 | ## 创建虚拟环境
31 |
32 | * * *
33 |
34 | 创建一个名为`python_project`的新目录,并将当前工作目录更改为`python_project`。
35 |
36 | ```py
37 | mkdir python_project
38 | cd python_project
39 |
40 | ```
41 |
42 | 要在`python_project`中创建虚拟环境,您需要发出以下命令。
43 |
44 | ```py
45 | virtualenv my_env
46 |
47 | ```
48 |
49 | 这将在`python_project`内创建一个新文件夹`my_env`。 此文件夹将包含用于安装包的 python 可执行文件和`pip`库的副本。 在这里,我们使用`my_env`作为名称,但是您可以使用任何您想要的名称。 现在您可以使用虚拟环境了,您只需要激活它即可。
50 |
51 | 在本教程中,我们有一点要使用 python 3.4 安装了`virtualenv`,假设您也有 python 2.7 并想创建一个使用 python 2.7 而不是 3.4 的虚拟环境,则可以使用以下命令进行操作。
52 |
53 | ```py
54 | virtualenv -p c:\Python27/python.exe my_env
55 |
56 | ```
57 |
58 | ## 激活虚拟环境
59 |
60 | * * *
61 |
62 | 如果您在 Windows 上,则需要执行以下命令。
63 |
64 | ```py
65 | my_env\Scripts\activate.bat
66 |
67 | ```
68 |
69 | 在 Linux 上,请输入。
70 |
71 | ```py
72 | source my_env/bin/activate
73 |
74 | ```
75 |
76 | 发出上述命令后,您的命令提示符字符串将发生变化,看起来像这样,
77 |
78 | ```py
79 | ( my_env ) Path_to_the_project: $
80 |
81 | ```
82 |
83 | 注意`( my_env )`,这表明您现在正在虚拟环境下运行。
84 |
85 | 现在您的虚拟环境已激活。 您在此处安装的所有内容仅会被该项目使用。
86 |
87 | 让我们尝试安装请求包。
88 |
89 | 在 Windows 中,输入以下代码。
90 |
91 | ```py
92 | my_env\Scripts\pip.exe install requests
93 |
94 | ```
95 |
96 | 您不能在 Windows 中仅使用`pip`安装请求,因为如果将`C:\Python34\Scripts`添加到`PATH`环境变量中,它将执行全局`pip`。 如果尚未添加,则会出现错误。
97 |
98 | 同样,在 Linux 中,您需要执行以下代码
99 |
100 | ```py
101 | my_env\Scripts\pip install requests
102 |
103 | ```
104 |
105 | ## 停用虚拟环境
106 |
107 | * * *
108 |
109 | 要停用虚拟环境,您需要使用以下命令。
110 |
111 | ```py
112 | deactivate
113 |
114 | ```
115 |
116 | 此命令将使您返回系统的默认 python 解释器,我们可以在其中将包安装在全局站点包中。
117 |
118 | 您现在应该能够看到使用`virtualenv`的动机。 它可以帮助我们组织项目的需求而不会相互冲突。
119 |
120 | * * *
121 |
122 | * * *
--------------------------------------------------------------------------------
/docs/3.md:
--------------------------------------------------------------------------------
1 | # python 入门
2 |
3 | > 原文: [https://thepythonguru.com/getting-started-with-python/](https://thepythonguru.com/getting-started-with-python/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | ## 什么是 Python?
12 |
13 | * * *
14 |
15 | Python 是 Guido Van Rossum 创建的通用编程语言。 如果您刚刚开始编程生涯,Python 因其优雅的语法和可读代码而广受赞誉。Python 最适合您。 使用 Python,您可以完成 GUI 开发,Web 应用,系统管理任务,财务计算,数据分析,可视化以及列表等所有工作。
16 |
17 | ## Python 是一种解释语言
18 |
19 | * * *
20 |
21 | 是的,Python 是解释语言,当您运行 python 程序时,解释器将逐行解析 python 程序,而 C 或 C++ 等已编译的语言则先编译该程序然后开始运行。
22 |
23 | 现在您可能会问,那有什么区别?
24 |
25 | 区别在于,与编译语言相比,解释语言要慢一些。 是的,如果使用 C 或 C++ 等编译语言编写代码,则绝对会获得一些性能上的好处。
26 |
27 | 但是用这种语言编写代码对于初学者来说是艰巨的任务。 同样在这种语言中,您甚至需要编写大多数基本功能,例如计算数组的长度,分割字符串等。对于更高级的任务,有时您需要创建自己的数据结构以将数据封装在程序中。 因此,在 C/C++ 中,在真正开始解决业务问题之前,您需要注意所有次要细节。 这就是 Python 来的地方。 在 Python 中,您不需要定义任何数据结构,也不需要定义小型工具函数,因为 Python 可以帮助您入门。
28 |
29 | 此外,Python 在 [https://pypi.python.org/](https://pypi.python.org/) 上提供了数百个可用的库,您可以在项目中使用它们而无需重新设计轮子。
30 |
31 | ## Python 是动态类型的
32 |
33 | * * *
34 |
35 | Python 不需要您提前定义变量数据类型。 Python 根据其包含的值的类型自动推断变量的数据类型。
36 |
37 | 例如:
38 |
39 | ```py
40 | myvar = "Hello Python"
41 |
42 | ```
43 |
44 | 上面的代码行将字符串`"Hello Python"`分配给变量`myvar`,因此`myvar`的类型为字符串。
45 |
46 | 请注意,与 C,C++ 和 Java 之类的语言不同,在 Python 中,您不需要以分号(`;`)结尾的语句。
47 |
48 | 假设稍后在程序中我们为变量`myvar`分配了`1`的值,即
49 |
50 | ```py
51 | myvar = 1
52 |
53 | ```
54 |
55 | 现在`myvar`变量的类型为`int`。
56 |
57 | ## Python 是强类型的
58 |
59 | * * *
60 |
61 | 如果您使用 PHP 或 javascript 编程。 您可能已经注意到,它们都将一种类型的数据自动转换为另一种类型。
62 |
63 | For e.g:
64 |
65 | 在 JavaScript 中
66 |
67 | ```py
68 | 1 + "2"
69 |
70 | ```
71 |
72 | 将是`'12'`
73 |
74 | 在这里,在进行加法(`+`)之前,`1`将转换为字符串并连接到`"2"`,这将导致`'12'`成为字符串。 但是,在 Python 中,不允许进行此类自动转换,因此
75 |
76 | ```py
77 | 1 + "2"
78 |
79 | ```
80 |
81 | 会产生一个错误。
82 |
83 | 试试看:
84 |
85 | ```py
86 | # run this code to see the error
87 | 1 + "2"
88 | ```
89 |
90 | ## 编写更少的代码,做更多的事情
91 |
92 | * * *
93 |
94 | 用 Python 编写的程序通常是 Java 代码的 1/3 或 1/5。 这意味着我们可以用 Python 编写更少的代码来实现与 Java 相同的功能。
95 |
96 | 要在 Python 中读取文件,您只需要两行代码:
97 |
98 | ```py
99 | with open("myfile.txt") as f:
100 | print(f.read())
101 |
102 | ```
103 |
104 | 试一试:
105 |
106 | ```py
107 | # these two lines create a file "myfile.txt" with data "Learning Python"
108 | with open("myfile.txt", "w") as f:
109 | f.write("Learning Python")
110 |
111 | # these two lines read data from myfile.txt
112 | with open("myfile.txt") as f:
113 | print(f.read())
114 | ```
115 |
116 | 不要太在意用于读写文件的命令。 我们将在以后的文章中学习所有内容。
117 |
118 | ## 谁使用 Python
119 |
120 | * * *
121 |
122 | 许多大型组织(例如 Google,NASA,Quora,HortonWorks 等)都使用 Python。
123 |
124 | 好的,我可以开始用 Python 构建什么?
125 |
126 | 您想要的几乎任何东西。 例如:
127 |
128 | * GUI 应用
129 | * 网络应用
130 | * 从网站抓取数据
131 | * 分析数据
132 | * 系统管理工具
133 | * 游戏开发
134 | * 数据科学
135 |
136 | 还有很多 ...
137 |
138 | 在下一篇文章中,我们将学习[如何安装 Python](/installing-python3/) 。
139 |
140 | * * *
141 |
142 | * * *
--------------------------------------------------------------------------------
/docs/30.md:
--------------------------------------------------------------------------------
1 | # Python 递归函数
2 |
3 | > 原文: [https://thepythonguru.com/python-recursive-functions/](https://thepythonguru.com/python-recursive-functions/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 函数本身调用时称为递归。 递归的工作原理类似于循环,但有时使用递归比循环更有意义。 您可以将任何循环转换为递归。
12 |
13 | 这是递归的工作方式。 递归函数会自行调用。 如您所料,如果不因某种条件而停止,则此过程将无限期重复。 此条件称为基本条件。 每个递归程序中都必须有一个基本条件,否则它将像无限循环一样永远继续执行。
14 |
15 | 递归函数的工作原理概述:
16 |
17 | 1. 递归函数由一些外部代码调用。
18 | 2. 如果满足基本条件,则程序执行有意义的操作并退出。
19 | 3. 否则,函数将执行一些必需的处理,然后调用自身以继续递归。 这是用于计算阶乘的递归函数的示例。
20 |
21 | 阶乘由数字表示,后跟(`!`)符号,即`4!`。
22 |
23 | 例如:
24 |
25 | ```py
26 | 4! = 4 * 3 * 2 * 1
27 | 2! = 2 * 1
28 | 0! = 1
29 |
30 | ```
31 |
32 | 这是一个例子
33 |
34 | ```py
35 | def fact(n):
36 | if n == 0:
37 | return 1
38 | else:
39 | return n * fact(n-1)
40 |
41 | print(fact(0))
42 | print(fact(5))
43 |
44 | ```
45 |
46 | **预期输出**:
47 |
48 | ```py
49 | 1
50 | 120
51 |
52 | ```
53 |
54 | ```py
55 | def fact(n):
56 | if n == 0:
57 | return 1
58 | else:
59 | return n * fact(n-1)
60 |
61 | print(fact(0))
62 | print(fact(5))
63 | ```
64 |
65 | 现在尝试执行上述函数:
66 |
67 | ```py
68 | print(fact(2000))
69 |
70 | ```
71 |
72 | 你会得到:
73 |
74 | ```py
75 | RuntimeError: maximum recursion depth exceeded in comparison
76 |
77 | ```
78 |
79 | 发生这种情况是因为默认情况下 python 在`1000`调用之后停止了调用递归函数。 若要更改此行为,您需要按如下所示修改代码。
80 |
81 | ```py
82 | import sys
83 | sys.setrecursionlimit(3000)
84 |
85 | def fact(n):
86 | if n == 0:
87 | return 1
88 | else:
89 | return n * fact(n-1)
90 |
91 | print(fact(2000))
92 |
93 | ```
94 |
95 | ```py
96 | import sys
97 | sys.setrecursionlimit(3000)
98 |
99 | def fact(n):
100 | if n == 0:
101 | return 1
102 | else:
103 | return n * fact(n-1)
104 |
105 | print(fact(2000))
106 | ```
107 |
108 | * * *
109 |
110 | * * *
--------------------------------------------------------------------------------
/docs/31.md:
--------------------------------------------------------------------------------
1 | # `__name__ == "__main__"`是什么?
2 |
3 | > 原文: [https://thepythonguru.com/what-is-if-__name__-__main__/](https://thepythonguru.com/what-is-if-__name__-__main__/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | Python 中的每个模块都有一个称为`__name__`的特殊属性。 当模块作为主程序运行时,`__name__`属性的值设置为`'__main__'`。 否则,将`__name__`的值设置为包含模块的名称。
12 |
13 | 考虑以下代码,以更好地理解。
14 |
15 | ```py
16 | # file my_module.py
17 |
18 | foo = 100
19 |
20 | def hello():
21 | print("i am from my_module.py")
22 |
23 | if __name__ == "__main__":
24 | print("Executing as main program")
25 | print("Value of __name__ is: ", __name__)
26 | hello()
27 |
28 | ```
29 |
30 | 在这里,我们定义了一个新模块`my_module`。 通过输入以下代码,我们可以将该模块作为主程序执行:
31 |
32 | ```py
33 | python my_module.py
34 |
35 | ```
36 |
37 | **预期输出**:
38 |
39 | ```py
40 | Executing as main program
41 | Value of __name__ is: __main__
42 | i am from my_module.py
43 |
44 | ```
45 |
46 | ```py
47 | # file my_module.py
48 |
49 | foo = 100
50 |
51 | def hello():
52 | print("i am from my_module.py")
53 |
54 | if __name__ == "__main__":
55 | print("Executing as main program")
56 | print("Value of __name__ is: ", __name__)
57 | hello()
58 | ```
59 |
60 | 在这里,我们正在创建一个新模块并将其作为主程序执行,因此`__name__`的值设置为`'__main__'`。 结果,如果条件满足,则函数`hello()`被调用。
61 |
62 | 现在创建一个名为`module.py`的新文件,并编写以下代码:
63 |
64 | ```py
65 | import my_module
66 |
67 | print(my_module.foo)
68 | my_module.hello()
69 |
70 | print(my_module.__name__)
71 |
72 | ```
73 |
74 | **预期输出**:
75 |
76 | ```py
77 | 100
78 | i am from my_module.py
79 | my_module
80 |
81 | ```
82 |
83 | 如您现在所见,由于`__name__`的值设置为`'my_module'`,因此`my_module`中的`if`语句执行失败。
84 |
85 | * * *
86 |
87 | * * *
--------------------------------------------------------------------------------
/docs/32.md:
--------------------------------------------------------------------------------
1 | # Python Lambda 函数
2 |
3 | > 原文: [https://thepythonguru.com/python-lambda-function/](https://thepythonguru.com/python-lambda-function/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | Python 允许您使用称为 lambda 函数的工具来创建匿名函数,即没有名称的函数。
12 |
13 | Lambda 函数是小的函数,通常不超过一行。 就像普通函数一样,它可以具有任意数量的参数。 lambda 函数的主体非常小,仅包含一个表达式。 表达式的结果是将 lambda 应用于参数时的值。 另外,lambda 函数中无需任何`return`语句。
14 |
15 | 让我们举个例子:
16 |
17 | 考虑一个函数`multiply()`:
18 |
19 | ```py
20 | def multiply(x, y):
21 | return x * y
22 |
23 | ```
24 |
25 | 此函数太小,因此让我们将其转换为 lambda 函数。
26 |
27 | 要创建 lambda 函数,请首先编写关键字`lambda`,然后是多个以逗号分隔的参数(`,`),然后是冒号 a(`:`),然后是单行表达式。
28 |
29 | ```py
30 | r = lambda x, y: x * y
31 | r(12, 3) # call the lambda function
32 |
33 | ```
34 |
35 | **预期输出**:
36 |
37 | ```py
38 | 36
39 |
40 | ```
41 |
42 | ```py
43 | r = lambda x, y: x * y
44 | print(r(12, 3)) # call the lambda function
45 | ```
46 |
47 | 在这里,我们使用两个参数`x`和`y`,冒号后面的表达式是 lambda 函数的主体。 如您所见,lambda 函数没有名称,并通过分配给它的变量进行调用。
48 |
49 | 您无需将 lambda 函数分配给变量。
50 |
51 | ```py
52 | (lambda x, y: x * y)(3,4)
53 |
54 | ```
55 |
56 | **预期输出**:
57 |
58 | ```py
59 | 12
60 |
61 | ```
62 |
63 | ```py
64 | print( (lambda x, y: x * y)(3,4) )
65 | ```
66 |
67 | 请注意,lambda 函数不能包含多个表达式。
68 |
69 | * * *
70 |
71 | * * *
--------------------------------------------------------------------------------
/docs/33.md:
--------------------------------------------------------------------------------
1 | # Python 字符串格式化
2 |
3 | > 原文: [https://thepythonguru.com/python-string-formatting](https://thepythonguru.com/python-string-formatting)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | `format()`方法允许您以任何所需的方式格式化字符串。
12 |
13 | **语法**: `template.format(p1, p1, .... , k1=v1, k2=v2)`
14 |
15 | 模板是一个包含格式代码的字符串,`format()`方法使用它的参数替换每个格式代码的值。 例如:
16 |
17 | ```py
18 | >>> 'Sam has {0} red balls and {1} yellow balls'.format(12, 31)
19 |
20 | ```
21 |
22 | `{0}`和`{1}`是格式代码。 格式代码`{0}`替换为`format()`的第一个参数,即`12`,而`{1}`替换为`format()`的第二个参数,即`31`。
23 |
24 | **预期输出**:
25 |
26 | ```py
27 | Sam has 12 red balls and 31 yellow balls
28 |
29 | ```
30 |
31 | 对于简单的格式化,该技术是可以的,但是如果要在浮点数中指定精度怎么办? 对于这种情况,您需要了解有关格式代码的更多信息。 这是格式代码的完整语法。
32 |
33 | **语法**: `{[argument_index_or_keyword]:[width][.precision][type]}`
34 |
35 | `type`可以与格式代码一起使用:
36 |
37 | | 格式码 | 描述 |
38 | | --- | --- |
39 | | `d` | 用于整数 |
40 | | `f` | 用于浮点数 |
41 | | `b` | 用于二进制数 |
42 | | `o` | 八进制数 |
43 | | `x` | 八进制十六进制数 |
44 | | `s` | 用于字符串 |
45 | | `e` | 用于指数格式的浮点 |
46 |
47 | 以下示例将使事情更加清楚。
48 |
49 | **示例 1**:
50 |
51 | ```py
52 | >>> "Floating point {0:.2f}".format(345.7916732)
53 |
54 | ```
55 |
56 | 在这里,我们指定精度的`2`位,`f`用于表示浮点数。
57 |
58 | **预期输出**:
59 |
60 | ```py
61 | Floating point 345.79
62 |
63 | ```
64 |
65 | **示例 2**:
66 |
67 | ```py
68 | >>> import math
69 | >>> "Floating point {0:10.3f}".format(math.pi)
70 |
71 | ```
72 |
73 | 在这里,我们指定`3`精度数字,`10`表示宽度,`f`表示浮点数。
74 |
75 | **预期输出**:
76 |
77 | ```py
78 | Floating point 3.142
79 |
80 | ```
81 |
82 | **示例 3**:
83 |
84 | ```py
85 | "Floating point pi = {0:.3f}, with {1:d} digit precision".format(math.pi, 3)
86 |
87 | ```
88 |
89 | 这里`{1:d}`中的`d`表示整数值。
90 |
91 | **预期输出**:
92 |
93 | ```py
94 | Floating point pi = 3.142, with 3 digit precision
95 |
96 | ```
97 |
98 | 如果为整数`ValueError`指定精度,则仅在浮点数的情况下才需要指定精度。
99 |
100 | **示例 5**:
101 |
102 | ```py
103 | 'Sam has {1:d} red balls and {0:d} yellow balls'.format(12, 31)
104 |
105 | ```
106 |
107 | **预期输出**:
108 |
109 | ```py
110 | Sam has 31 red balls and 12 yellow balls
111 |
112 | ```
113 |
114 | **示例 6**:
115 |
116 | ```py
117 | "In binary 4 is {0:b}".format(4) # b for binary, refer to Fig 1.1
118 |
119 | ```
120 |
121 | **预期输出**:
122 |
123 | ```py
124 | In binary 4 is 100
125 |
126 | ```
127 |
128 | **示例 7**:
129 |
130 | ```py
131 | array = [34, 66, 12]
132 | "A = {0}, B = {1}, C = {2}".format(*array)
133 |
134 | ```
135 |
136 | **预期输出**:
137 |
138 | ```py
139 | A = 34, B = 66, C = 12
140 |
141 | ```
142 |
143 | **示例 8**:
144 |
145 | ```py
146 | d = {
147 | 'hats' : 122,
148 | 'mats' : 42
149 | }
150 |
151 | "Sam had {hats} hats and {mats} mats".format(**d)
152 |
153 | ```
154 |
155 | **预期输出**:
156 |
157 | ```py
158 | Sam had 122 hats and 42 mats
159 |
160 | ```
161 |
162 | `format()`方法还支持关键字参数。
163 |
164 | ```py
165 | 'Sam has {red} red balls and {green} yellow balls'.format(red = 12, green = 31)
166 |
167 | ```
168 |
169 | 请注意,在使用关键字参数时,我们需要在`{}`内部使用参数,而不是数字索引。
170 |
171 | 您还可以将位置参数与关键字参数混合
172 |
173 | ```py
174 | 'Sam has {red} red balls, {green} yellow balls \
175 | and {0} bats'.format(3, red = 12, green = 31)
176 |
177 | ```
178 |
179 | 格式化字符串的`format()`方法是一个非常新的方法,它是在 Python 2.6 中引入的。 您将在旧版代码中看到另一种古老的技术,它允许您使用`%`运算符而不是`format()`方法来格式化字符串。
180 |
181 | 让我们举个例子。
182 |
183 | ```py
184 | "%d pens cost = %.2f" % (12, 150.87612)
185 |
186 | ```
187 |
188 | 在这里,我们使用`%`左侧的模板字符串。 我们使用`%`代替格式代码的`{}`。 在`%`的右侧,我们使用元组包含我们的值。 `%d`和`%.2f`被称为格式说明符,它们以`%`开头,后跟代表数据类型的字符。 例如,`%d`格式说明符是整数的占位符,类似地`%.2f`是浮点数的占位符。
189 |
190 | 因此,`%d`被替换为元组的第一值,即`12`,而`%.2f`被替换为第二值,即`150.87612`。
191 |
192 | **预期输出**:
193 |
194 | ```py
195 | 12 pens cost = 150.88
196 |
197 | ```
198 |
199 | 一些更多的例子。
200 |
201 | **示例 1**:
202 |
203 | 新:
204 |
205 | ```py
206 | "{0:d} {1:d} ".format(12, 31)
207 |
208 | ```
209 |
210 | 旧:
211 |
212 | ```py
213 | "%d %d" % (12, 31)
214 |
215 | ```
216 |
217 | **预期输出**:
218 |
219 | ```py
220 | 12 31
221 |
222 | ```
223 |
224 | **示例 2**:
225 |
226 | New:
227 |
228 | ```py
229 | "{0:.2f} {1:.3f}".format(12.3152, 89.65431)
230 |
231 | ```
232 |
233 | Old:
234 |
235 | ```py
236 | "%.2f %.3f" % (12.3152, 89.65431)
237 |
238 | ```
239 |
240 | **预期输出**:
241 |
242 | ```py
243 | 12.32 89.654
244 |
245 | ```
246 |
247 | **示例 3**:
248 |
249 | New:
250 |
251 | ```py
252 | "{0:s} {1:o} {2:.2f} {3:d}".format("Hello", 71, 45836.12589, 45 )
253 |
254 | ```
255 |
256 | Old:
257 |
258 | ```py
259 | "%s %o %.2f %d" % ("Hello", 71, 45836.12589, 45 )
260 |
261 | ```
262 |
263 | **预期输出**:
264 |
265 | ```py
266 | Hello 107 45836.13 45
267 |
268 | ```
269 |
270 | * * *
271 |
272 | * * *
--------------------------------------------------------------------------------
/docs/34.md:
--------------------------------------------------------------------------------
1 | # Python 内置函数和方法
--------------------------------------------------------------------------------
/docs/35.md:
--------------------------------------------------------------------------------
1 | # Python `abs()`函数
2 |
3 | > 原文: [https://thepythonguru.com/python-builtin-functions/abs/](https://thepythonguru.com/python-builtin-functions/abs/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | `abs()`函数返回数字的绝对值(大小无符号)。
12 |
13 | 其语法如下:
14 |
15 | ```py
16 | abs(x) -> absolute value
17 |
18 | ```
19 |
20 | | 参数 | 描述 |
21 | | --- | --- |
22 | | `x` | 任何数值 |
23 |
24 | 这是一个例子:
25 |
26 | ```py
27 | >>>
28 | >>> abs(-45)
29 | 45
30 | >>>
31 | >>>
32 | >>> abs(-3.14)
33 | 3.14
34 | >>>
35 | >>>
36 | >>> abs(10)
37 | 10
38 | >>>
39 | >>>
40 | >>> abs(2+4j)
41 | 4.47213595499958
42 | >>>
43 |
44 | ```
45 |
46 | ```py
47 | print(abs(-45))
48 | print(abs(-3.14))
49 | print(abs(10))
50 | print(abs(2+4j))
51 | ```
52 |
53 | 对于整数和浮点数,结果非常明显。 如果是`z = x + yi`的复数,则`abs()`函数将按如下方式计算绝对值:
54 |
55 | 绝对值:`|z| = √x² + y²`
56 |
57 | ```py
58 | => 2+4j
59 | => √2² + 4²
60 | => √4 + 16
61 | => √20
62 | => 2√5
63 | => 2*2.236
64 | => 4.472
65 |
66 | ```
67 |
68 | * * *
69 |
70 | * * *
--------------------------------------------------------------------------------
/docs/36.md:
--------------------------------------------------------------------------------
1 | # Python `bin()`函数
2 |
3 | > 原文: [https://thepythonguru.com/python-builtin-functions/bin/](https://thepythonguru.com/python-builtin-functions/bin/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | `bin()`函数以字符串形式返回整数的二进制表示形式。
12 |
13 | 其语法如下:
14 |
15 | ```py
16 | bin(number) -> binary representation
17 |
18 | ```
19 |
20 | | 参数 | 描述 |
21 | | --- | --- |
22 | | `number` | 任何数值 |
23 |
24 | 这是一个例子:
25 |
26 | ```py
27 | >>>
28 | >>> bin(4) # convert decimal to binary
29 | '0b100'
30 | >>>
31 | >>>
32 | >>> bin(0xff) # convert hexadecimal to binary, 0xff is same decimal 255
33 | '0b11111111'
34 | >>>
35 | >>>
36 | >>> bin(0o24) # convert octacl to binary, 0o24 is same decimal 20
37 | '0b10100'
38 | >>>
39 |
40 | ```
41 |
42 | ```py
43 | print(bin(4))
44 | print(bin(0xff))
45 | print(bin(0o24))
46 | ```
47 |
48 | ## `bin()`与用户定义的对象
49 |
50 | * * *
51 |
52 | 要将`bin()`与用户定义的对象一起使用,我们必须首先重载`__index__()`方法。 在切片和索引的上下文中,`__index__()`方法用于将对象强制为整数。 例如,考虑以下内容:
53 |
54 | ```py
55 | >>>
56 | >>> l = [1, 2, 3, 4, 5]
57 | >>>
58 | >>> x, y = 1, 3
59 | >>>
60 | >>>
61 | >>> l[x]
62 | 2
63 | >>>
64 | >>>
65 | >>> l[y]
66 | 4
67 | >>>
68 | >>>
69 | >>> l[x:y]
70 | [2, 3]
71 | >>>
72 |
73 | ```
74 |
75 | ```py
76 | l = [1, 2, 3, 4, 5]
77 | x, y = 1, 3
78 | print(l[x])
79 | print(l[y])
80 | print(l[x:y])
81 | ```
82 |
83 | 当我们使用索引和切片访问列表中的项目时,内部 Python 会调用`int`对象的`__index__()`方法。
84 |
85 | ```py
86 | >>>
87 | >>> l[x.__index__()] # same as l[x]
88 | 2
89 | >>>
90 | >>>
91 | >>> l[y.__index__()] # same as l[y]
92 | 4
93 | >>>
94 | >>>
95 | >>> l[x.__index__():y.__index__()] # # same as l[x:y]
96 | [2, 3]
97 | >>>
98 |
99 | ```
100 |
101 | ```py
102 | l = [1, 2, 3, 4, 5]
103 | x, y = 1, 3
104 | print(l[x.__index__()])
105 | print(l[y.__index__()])
106 | print(l[x.__index__():y.__index__()])
107 | ```
108 |
109 | 除了`bin()`之外,在对象上调用`hex()`和`oct()`时也会调用`__index__()`方法。 这是一个例子:
110 |
111 | ```py
112 | >>>
113 | >>> class Num:
114 | ... def __index__(self):
115 | ... return 4
116 | ...
117 | >>>
118 | >>> l = [1, 2, 3, 4, 5]
119 | >>>
120 | >>>
121 | >>> n1 = Num()
122 | >>>
123 | >>>
124 | >>> bin(n1)
125 | 0b100
126 | >>>
127 | >>>
128 | >>> hex(n1)
129 | 0x4
130 | >>>
131 | >>>
132 | >>> oct(n1)
133 | 0o4
134 | >>>
135 | >>>
136 | >>> l[n1]
137 | 5
138 | >>>
139 | >>>
140 | >>> l[n1.__index__()]
141 | 5
142 | >>>
143 |
144 | ```
145 |
146 | ```py
147 | class Num:
148 | def __index__(self):
149 | return 4
150 |
151 | l = [1, 2, 3, 4, 5]
152 |
153 | n1 = Num()
154 |
155 | print(bin(n1))
156 | print(hex(n1))
157 | print(oct(n1))
158 | print(l[n1])
159 | print(l[n1.__index__()])
160 | ```
161 |
162 | * * *
163 |
164 | * * *
--------------------------------------------------------------------------------
/docs/37.md:
--------------------------------------------------------------------------------
1 | # Python `id()`函数
2 |
3 | > 原文: [https://thepythonguru.com/python-builtin-functions/id/](https://thepythonguru.com/python-builtin-functions/id/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | `id()`函数返回与对象关联的唯一数字标识符。
12 |
13 | 在标准 Python(即 CPython)中,标识符表示对象的内存地址。 虽然,这在其他实现中可能会有所不同。
14 |
15 | 定义对象时,唯一标识符会自动存在,并且在程序运行之前不会更改。 我们可以使用此标识符来确定两个对象是否相同。
16 |
17 | `id()`函数的语法如下:
18 |
19 | ```py
20 | id(obj) -> unique identifier
21 |
22 | ```
23 |
24 | 这是一个例子:
25 |
26 | ```py
27 | >>>
28 | >>> a = 10
29 | >>>
30 | >>> b = 5
31 | >>>
32 | >>>
33 | >>> id(a), id(b)
34 | (10919712, 10919552)
35 | >>>
36 | >>>
37 | >>> a = b # a now references same object as b
38 | >>>
39 | >>>
40 | >>> id(a), id(b)
41 | (10919552, 10919552)
42 | >>>
43 |
44 | ```
45 |
46 | ```py
47 | a = 10
48 | b = 5
49 |
50 | print(id(a), id(b))
51 |
52 | a = b # a now references same object as b
53 |
54 | print(id(a), id(b))
55 | ```
56 |
57 | 最初,变量`a`和`b`引用两个不同的对象。 结果,`id()`调用返回两个唯一标识符。 接下来,我们将对象`b`分配给`a`。 现在,`a`和`b`引用相同的对象(`5`)。 因此,下一个`id()`调用返回相同的标识符。
58 |
59 | * * *
60 |
61 | * * *
--------------------------------------------------------------------------------
/docs/38.md:
--------------------------------------------------------------------------------
1 | # Python `map()`函数
2 |
3 | > 原文: [https://thepythonguru.com/python-builtin-functions/map/](https://thepythonguru.com/python-builtin-functions/map/)
4 |
5 | * * *
6 |
7 | 于 2020 年 1 月 7 日更新
8 |
9 | * * *
10 |
11 | 将`map()`内置函数应用于序列中的每个项目后,它会返回一个迭代器。 其语法如下:
12 |
13 | **语法**: `map(function, sequence[, sequence, ...]) -> map object`
14 |
15 | **Python 3**
16 |
17 | ```py
18 | >>>
19 | >>> map(ord, ['a', 'b', 'c', 'd'])
20 |