├── .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 | ![](http://data.apachecn.org/img/about/donate.jpg) 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 |
8 |

我们一直在努力

9 |

${unRepo}

10 |

11 | 12 | 13 | iBooker 面试求职

14 |

15 |
16 | 20 |
21 |
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 | 3 | 4 | Edit 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /asset/left.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1210 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /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:/![sra](?=[:}]$)/,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 | 3 | 4 | 1209 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /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
\n \n \n \n \n \n
\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 | 3 | 4 | Share-1 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /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 | 3 | 4 | 1211 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /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 | ![python-exception-classes.jpg](img/72eeb7f2bbb92ad38bfff7f133d3c3cc.png) 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 | 21 | >>> 22 | >>> list(map(ord, ['a', 'b', 'c', 'd'])) 23 | >>> [97, 98, 99, 100] 24 | >>> 25 | 26 | ``` 27 | 28 | ```py 29 | map_obj = map(ord, ['a', 'b', 'c', 'd']) 30 | print(map_obj) 31 | print(list(map_obj)) 32 | ``` 33 | 34 | 在此,列表中的项目一次被传递到`ord()`内置函数。 35 | 36 | 由于`map()`返回一个迭代器,因此我们使用了`list()`函数立即生成结果。 37 | 38 | 上面的代码在功能上等同于以下代码: 39 | 40 | **Python 3** 41 | 42 | ```py 43 | >>> 44 | >>> ascii = [] 45 | >>> 46 | >>> for i in ['a', 'b', 'c', 'd']: 47 | ... ascii.append(ord(i)) 48 | ... 49 | >>> 50 | >>> ascii 51 | [97, 98, 99, 100] 52 | >>> 53 | 54 | ``` 55 | 56 | ```py 57 | ascii = [] 58 | 59 | for i in ['a', 'b', 'c', 'd']: 60 | ascii.append(ord(i)) 61 | 62 | print(ascii) 63 | ``` 64 | 65 | 但是,使用`map()`会导致代码缩短,并且通常运行速度更快。 66 | 67 | 在 Python 2 中,`map()`函数返回一个列表,而不是一个迭代器(就内存消耗而言,这不是很有效),因此我们无需在`list()`调用中包装`map()`。 68 | 69 | **Python 2** 70 | 71 | ```py 72 | >>> 73 | >>> map(ord, ['a', 'b', 'c', 'd']) # in Python 2 74 | [97, 98, 99, 100] 75 | >>> 76 | 77 | ``` 78 | 79 | ## 传递用户定义的函数 80 | 81 | * * * 82 | 83 | 在下面的清单中,我们将用户定义的函数传递给`map()`函数。 84 | 85 | **Python 3** 86 | 87 | ```py 88 | >>> 89 | >>> def twice(x): 90 | ... return x*2 91 | ... 92 | >>> 93 | >>> list(map(twice, [11,22,33,44,55])) 94 | [22, 44, 66, 88, 110] 95 | >>> 96 | 97 | ``` 98 | 99 | ```py 100 | def twice(x): 101 | return x*2 102 | 103 | print(list(map(twice, [11,22,33,44,55]))) 104 | ``` 105 | 106 | 在此,该函数将列表中的每个项目乘以 2。 107 | 108 | ## 传递多个参数 109 | 110 | * * * 111 | 112 | 如果我们将`n`序列传递给`map()`,则该函数必须采用`n`个参数,并且并行使用序列中的项,直到用尽最短的序列。 但是在 Python 2 中,当最长的序列被用尽时,`map()`函数停止,而当较短的序列被用尽时,`None`的值用作填充。 113 | 114 | **Python 3** 115 | 116 | ```py 117 | >>> 118 | >>> def calc_sum(x1, x2): 119 | ... return x1+x2 120 | ... 121 | >>> 122 | >>> list(map(calc_sum, [1, 2, 3, 4, 5], [10, 20, 30])) 123 | [11, 22, 33] 124 | >>> 125 | 126 | ``` 127 | 128 | ```py 129 | def calc_sum(x1, x2): 130 | return x1+x2 131 | 132 | map_obj = list(map(calc_sum, [1, 2, 3, 4, 5], [10, 20, 30])) 133 | print(map_obj) 134 | ``` 135 | 136 | **Python 2** 137 | 138 | ```py 139 | >>> 140 | >>> def foo(x1, x2): 141 | ... if x2 is None: 142 | ... return x1 143 | ... else: 144 | ... return x1+x2 145 | ... 146 | >>> 147 | >>> list(map(foo, [1, 2, 3, 4, 5], [10, 20, 30])) 148 | [11, 22, 33, 4, 5] 149 | >>> 150 | 151 | ``` 152 | 153 | ## 传递 Lambda 154 | 155 | * * * 156 | 157 | 如果您的函数不打算被重用,则可以传递 lambda(内联匿名函数)而不是函数。 158 | 159 | **Python 3** 160 | 161 | ```py 162 | >>> 163 | >>> list(map(lambda x1:x1*5, [1, 2, 3])) 164 | [5, 10, 15] 165 | >>> 166 | 167 | ``` 168 | 169 | ```py 170 | map_obj = map(lambda x1:x1*5, [1, 2, 3]) 171 | print(list(map_obj)) 172 | ``` 173 | 174 | 在此,该函数将列表中的每个项目乘以 5。 175 | 176 | ## 配对项目(仅在 Python 2 中) 177 | 178 | * * * 179 | 180 | 最后,您可以通过传递`None`代替函数来配对多个序列中的项目: 181 | 182 | **Python 2** 183 | 184 | ```py 185 | >>> 186 | >>> map(None, "hello", "pi") 187 | [('h', 'p'), ('e', 'i'), ('l', None), ('l', None), ('o', None)] 188 | >>> 189 | 190 | ``` 191 | 192 | 请注意,当较短的序列用尽时,将使用`None`填充结果。 193 | 194 | 这种形式的`map()`在 Python 3 中无效。 195 | 196 | ```py 197 | >>> 198 | >>> list(map(None, "hello", "pi")) 199 | Traceback (most recent call last): 200 | File "", line 1, in 201 | TypeError: 'NoneType' object is not callable 202 | >>> 203 | 204 | ``` 205 | 206 | ```py 207 | print(list(map(None, "hello", "pi"))) 208 | ``` 209 | 210 | 如果要配对多个序列中的项目,请使用[`zip()`](/python-zip-function/)函数。 211 | 212 | * * * 213 | 214 | * * * -------------------------------------------------------------------------------- /docs/39.md: -------------------------------------------------------------------------------- 1 | # Python `zip()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/zip/](https://thepythonguru.com/python-builtin-functions/zip/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `zip()`函数采用一个或多个序列,并将序列中的对应项组合成一个元组。 最短序列用完时它将停止。 在 Python 2 中,`zip()`返回一个实际的列表,如果您处理大量数据则效率不高。 因此,在 Python 3 中,`zip()`返回一个可迭代的对象,该对象可按需生成结果。 12 | 13 | **语法**:`zip(iter1 [,iter2 [...]]) --> zip object` 14 | 15 | **Python 3** 16 | 17 | ```py 18 | >>> 19 | >>> zip([1, 2, 3, 4], "pow") 20 | 21 | >>> 22 | 23 | ``` 24 | 25 | 要产生结果,请在`list()`调用中包装`zip()`。 26 | 27 | ```py 28 | >>> 29 | >>> list(zip([1, 2, 3, 4], "pow")) 30 | [(1, 'p'), (2, 'o'), (3, 'w')] 31 | >>> 32 | 33 | ``` 34 | 35 | 试试看: 36 | 37 | ```py 38 | zip_obj = zip([1, 2, 3, 4], "pow") 39 | print(list(zip_obj)) 40 | ``` 41 | 42 | **Python 2** 43 | 44 | ```py 45 | >>> 46 | >>> zip([1, 2, 3, 4], "pow") # In Python 2, list() call is not required 47 | [(1, 'p'), (2, 'o'), (3, 'w')] 48 | >>> 49 | 50 | ``` 51 | 52 | 这是一个实际示例,其中`zip()`用于并行迭代多个序列。 53 | 54 | ```py 55 | >>> 56 | >>> for i, j, k, l in zip([1, 2, 3], "foo", ("one", "two", "three"), {"alpha", "beta", "gamma"}): 57 | ... print(i, j, k, l) 58 | ... 59 | 1 f one alpha 60 | 2 o two gamma 61 | 3 o three beta 62 | >>> 63 | 64 | ``` 65 | 66 | 试一试: 67 | 68 | ```py 69 | for i, j, k, l in zip([1, 2, 3], "foo", 70 | ("one", "two", "three"), 71 | {"alpha", "beta", "gamma"} 72 | ): 73 | print(i, j, k, l) 74 | ``` 75 | 76 | 这是另一个使用`zip()`函数创建字典的示例。 77 | 78 | ```py 79 | >>> 80 | >>> keys = ['alpha', 'beta', 'gamma'] 81 | >>> values = [10, 20, 30] 82 | >>> 83 | >>> d = dict(zip(keys, values)) 84 | >>> d 85 | {'alpha': 10, 'beta': 20, 'gamma': 30} 86 | >>> 87 | 88 | ``` 89 | 90 | 试一试: 91 | 92 | ```py 93 | keys = ['alpha', 'beta', 'gamma'] 94 | values = [10, 20, 30] 95 | 96 | d = dict(zip(keys, values)) 97 | print(d) 98 | ``` 99 | 100 | * * * 101 | 102 | * * * -------------------------------------------------------------------------------- /docs/4.md: -------------------------------------------------------------------------------- 1 | # 安装 Python3 2 | 3 | > 原文: [https://thepythonguru.com/installing-python3/](https://thepythonguru.com/installing-python3/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | 本教程重点介绍 Python3。大多数 Linux 发行版,例如 Ubuntu 14.04,都安装了 python 2 和 3,这是下载链接。 如果您使用其他 Linux 发行版,请参阅此链接以获取安装说明。 Mac 还随附安装了 python 2 和 python 3(如果未查看此链接以获取说明),但 Windows 并非如此。 12 | 13 | **注意**: 14 | 15 | 注意:在本教程中,我将仅在 Windows 和 Ubuntu 14.04 上提供必要的说明。 16 | 17 | ## 在 Windows 中安装 Python 3 18 | 19 | * * * 20 | 21 | 要安装 python,您需要从 [https://www.python.org/downloads/](https://www.python.org/downloads/) 下载 python 二进制文件,特别是我们将使用 python 3.4.3,您可以在此处从[下载](https://www.python.org/downloads/release/python-343/) 。 安装时,请记住检查“将`Python.exe`添加到路径”(请参见下图)。 22 | 23 | ![install-python.png](img/fe7cf26a723283da03ef589149ee7c3c.png) 24 | 25 | 现在您已经安装了 python,打开命令提示符或终端并输入`python`。 现在您在 python shell 中。 26 | 27 | ![python-shell.png](img/1465df1cc7b49f4ef431f26f7e1627ab.png) 28 | 29 | 要测试一切正常,请在 python shell 中键入以下命令。 30 | 31 | ```py 32 | print("Hello World") 33 | 34 | ``` 35 | 36 | ![hello-python.png](img/ff8e1e812772d3d072395aa647df7499.png) 37 | 38 | **预期输出**: 39 | 40 | ```py 41 | Hello World 42 | 43 | ``` 44 | 45 | 如果您使用的是已随附 python 2 和 python 3 的 Ubuntu 14.04,则需要输入`python3`而不是仅`python`才能输入 python 3 shell。 46 | 47 | ![invoke-python3.png](img/08b661eaec8ff40dbd5e2fbc5e7bb843.png) 48 | 49 | 安装文本编辑器要编写 python 程序,您将需要一个文本编辑器,您可以使用文本编辑器(如记事本)。 如果要使用完整的文本编辑器,请使用 Notepad++ 或 SublimeText。 下载并安装您选择的文本编辑器。 50 | 51 | 现在您已经成功安装了 python 3 和文本编辑器,并准备继续进行下一章,在此我们将学习运行 python 程序的不同方法。 52 | 53 | * * * 54 | 55 | * * * -------------------------------------------------------------------------------- /docs/40.md: -------------------------------------------------------------------------------- 1 | # Python `filter()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/filter/](https://thepythonguru.com/python-builtin-functions/filter/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `filter()`函数将一个函数和一个序列作为参数并返回一个可迭代的对象,仅按顺序产生要为其返回`True`的项目。 如果传递了`None`而不是函数,则将求值为`False`的序列中的所有项目删除。 `filter()`的语法如下: 12 | 13 | **语法**: `filter(function or None, iterable) --> filter object` 14 | 15 | 这是一个例子: 16 | 17 | **Python 3** 18 | 19 | ```py 20 | >>> 21 | >>> def is_even(x): 22 | ... if x % 2 == 0: 23 | ... return True 24 | ... else: 25 | ... return False 26 | ... 27 | >>> 28 | >>> f = filter(is_even, [1, 3, 10, 45, 6, 50]) 29 | >>> 30 | >>> f 31 | 32 | >>> 33 | >>> 34 | >>> for i in f: 35 | ... print(i) 36 | ... 37 | 10 38 | 6 39 | 50 40 | >>> 41 | 42 | ``` 43 | 44 | 试试看: 45 | 46 | ```py 47 | def is_even(x): 48 | if x % 2 == 0: 49 | return True 50 | else: 51 | return False 52 | 53 | f = filter(is_even, [1, 3, 10, 45, 6, 50]) 54 | 55 | print(f) 56 | 57 | for i in f: 58 | print(i) 59 | ``` 60 | 61 | 要立即产生结果,我们可以使用`list()`函数。 62 | 63 | **Python 3** 64 | 65 | ```py 66 | >>> 67 | >>> list(filter(is_even, [1, 3, 10, 45, 6, 50])) 68 | [10, 6, 50] 69 | >>> 70 | >>> 71 | >>> list(filter(None, [1, 45, "", 6, 50, 0, {}, False])) # function argument is None 72 | [1, 45, 6, 50] 73 | >>> 74 | 75 | ``` 76 | 77 | 试一试: 78 | 79 | ```py 80 | def is_even(x): 81 | if x % 2 == 0: 82 | return True 83 | else: 84 | return False 85 | 86 | print( list(filter(is_even, [1, 3, 10, 45, 6, 50])) ) 87 | 88 | # function argument is None 89 | print( list(filter(None, [1, 45, "", 6, 50, 0, {}, False])) ) 90 | ``` 91 | 92 | 在 Python 2 中,`filter()`返回实际列表(这不是处理大数据的有效方法),因此您无需将`filter()`包装在`list()`调用中。 93 | 94 | **Python 2** 95 | 96 | ```py 97 | >>> 98 | >>> filter(is_even, [1, 3, 10, 45, 6, 50]) 99 | [10, 6, 50] 100 | >>> 101 | 102 | ``` 103 | 104 | 这是其他一些例子。 105 | 106 | **Python 3** 107 | 108 | ```py 109 | >>> 110 | >>> filter(lambda x: x % 2 != 0, [1, 3, 10, 45, 6, 50]) # lambda is used in place of a function 111 | [1, 3, 45] 112 | >>> 113 | >>> 114 | >>> list(filter(bool, [10, "", "py"])) 115 | [10, 'py'] 116 | >>> 117 | >>> 118 | >>> import os 119 | >>> 120 | >>> # display all files in the current directory (except the hidden ones) 121 | >>> list(filter(lambda x: x.startswith(".") != True, os.listdir(".") )) 122 | ['Documents', 'Downloads', 'Desktop', 'Pictures', 'bin', 'opt', 'Templates', 'Public', 'Videos', 'Music'] 123 | >>> 124 | 125 | ``` 126 | 127 | 试一试: 128 | 129 | ```py 130 | # lambda is used in place of a function 131 | print(filter(lambda x: x % 2 != 0, [1, 3, 10, 45, 6, 50])) 132 | 133 | print(list(filter(bool, [10, "", "py"]))) 134 | 135 | import os 136 | 137 | # display all files in the current directory (except the hidden ones) 138 | print(list(filter(lambda x: x.startswith(".") != True, os.listdir(".") )) ) 139 | ``` 140 | 141 | * * * 142 | 143 | * * * -------------------------------------------------------------------------------- /docs/41.md: -------------------------------------------------------------------------------- 1 | # Python `reduce()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/reduce/](https://thepythonguru.com/python-builtin-functions/reduce/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `reduce()`函数接受一个函数和一个序列并返回如下计算的单个值: 12 | 13 | 1. 最初,使用序列中的前两项调用该函数,然后返回结果。 14 | 2. 然后使用在步骤 1 中获得的结果和序列中的下一个值再次调用该函数。 这个过程一直重复,直到序列中有项目为止。 15 | 16 | `reduce()`函数的语法如下: 17 | 18 | **语法**:`reduce(function, sequence[, initial]) -> value` 19 | 20 | 提供`initial`值时,将使用`initial`值和序列中的第一项调用该函数。 21 | 22 | 在 Python 2 中,`reduce()`是一个内置函数。 但是,在 Python 3 中,它已移至`functools`模块。 因此,要使用它,必须先按以下步骤导入它: 23 | 24 | ```py 25 | from functools import reduce # only in Python 3 26 | 27 | ``` 28 | 29 | 这是添加列表中所有项目的示例。 30 | 31 | ```py 32 | >>> 33 | >>> from functools import reduce 34 | >>> 35 | >>> def do_sum(x1, x2): return x1 + x2 36 | ... 37 | >>> 38 | >>> reduce(do_sum, [1, 2, 3, 4]) 39 | 10 40 | >>> 41 | 42 | ``` 43 | 44 | 试试看: 45 | 46 | ```py 47 | from functools import reduce 48 | 49 | def do_sum(x1, x2): 50 | return x1 + x2 51 | 52 | print(reduce(do_sum, [1, 2, 3, 4])) 53 | ``` 54 | 55 | 此`reduce()`调用执行以下操作: 56 | 57 | ```py 58 | (((1 + 2) + 3) + 4) => 10 59 | 60 | ``` 61 | 62 | 前面的`reduce()`调用在功能上等同于以下内容: 63 | 64 | ```py 65 | >>> 66 | >>> def my_reduce(func, seq): 67 | ... first = seq[0] 68 | ... for i in seq[1:]: 69 | ... first = func(first, i) 70 | ... return first 71 | ... 72 | >>> 73 | >>> my_reduce(do_sum, [1, 2, 3, 4]) 74 | 10 75 | >>> 76 | 77 | ``` 78 | 79 | 试一试: 80 | 81 | ```py 82 | def do_sum(x1, x2): 83 | return x1 + x2 84 | 85 | def my_reduce(func, seq): 86 | first = seq[0] 87 | for i in seq[1:]: 88 | first = func(first, i) 89 | return first 90 | 91 | print(my_reduce(do_sum, [1, 2, 3, 4])) 92 | ``` 93 | 94 | 但是,`reduce()`调用比`for`循环更简洁,并且性能明显更好。 95 | 96 | * * * 97 | 98 | * * * -------------------------------------------------------------------------------- /docs/43.md: -------------------------------------------------------------------------------- 1 | # Python `enumerate()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/enumerate/](https://thepythonguru.com/python-builtin-functions/enumerate/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `enumerate()`函数采用一个可迭代对象,并返回一个枚举对象(一个迭代器),该对象生成一个格式为`(index, item)`的元组,其中`index`指该项目的偏移量,`item`指的是可迭代对象中的对应的项目。 12 | 13 | `enumerate()`函数的语法如下: 14 | 15 | **语法**: 16 | 17 | ```py 18 | enumerate(iterable[, start=0]) -> iterator for index, value of iterable 19 | 20 | ``` 21 | 22 | | 参数 | 描述 | 23 | | --- | --- | 24 | | `iterable` | (必需)任何可迭代的对象,例如字符串,列表,字典等。 | 25 | | `start`(可选) | `index`的初始值。 默认为`0`。 | 26 | 27 | 这是一个例子: 28 | 29 | ```py 30 | >>> 31 | >>> list(enumerate("hello")) 32 | [(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')] 33 | >>> 34 | >>> 35 | >>> for index, value in enumerate("hello"): 36 | ... print(index, value) 37 | ... 38 | 0 h 39 | 1 e 40 | 2 l 41 | 3 l 42 | 4 o 43 | >>> 44 | 45 | ``` 46 | 47 | 试试看: 48 | 49 | ```py 50 | print( list(enumerate("hello")) ) 51 | 52 | for index, value in enumerate("hello"): 53 | print(index, value) 54 | ``` 55 | 56 | 以下清单显示`enumerate()`如何与清单,字典和元组一起使用: 57 | 58 | ```py 59 | >>> 60 | >>> for index, value in enumerate([110, 45, 12, 891, "one"]): 61 | ... print(index, value) 62 | ... 63 | 0 110 64 | 1 45 65 | 2 12 66 | 3 891 67 | 4 one 68 | >>> 69 | >>> 70 | >>> for index, value in enumerate({'name': 'Jane', 'age': 26, 'salary': 40000}): 71 | ... print(index, value) 72 | ... 73 | 0 name 74 | 1 salary 75 | 2 age 76 | >>> 77 | >>> 78 | >>> for index, value in enumerate({1, 290, -88, 10}): 79 | ... print(index, value) 80 | ... 81 | 0 -88 82 | 1 1 83 | 2 10 84 | 3 290 85 | >>> 86 | 87 | ``` 88 | 89 | 试一试: 90 | 91 | ```py 92 | for index, value in enumerate([110, 45, 12, 891, "one"]): 93 | print(index, value) 94 | 95 | print("-"*20) 96 | 97 | for index, value in enumerate({'name': 'Jane', 'age': 26, 'salary': 40000}): 98 | print(index, value) 99 | 100 | print("-"*20) 101 | 102 | for index, value in enumerate({1, 290, -88, 10}): 103 | print(index, value) 104 | ``` 105 | 106 | ## 设置索引的初始值 107 | 108 | * * * 109 | 110 | 要设置索引的初始值,我们使用`start`关键字参数。 111 | 112 | ```py 113 | >>> 114 | >>> list(enumerate("hello", start=2)) 115 | [(2, 'h'), (3, 'e'), (4, 'l'), (5, 'l'), (6, 'o')] 116 | >>> 117 | >>> 118 | >>> for index, value in enumerate("hello", start=2): 119 | ... print(index, value) 120 | ... 121 | 2 h 122 | 3 e 123 | 4 l 124 | 5 l 125 | 6 o 126 | >>> 127 | 128 | ``` 129 | 130 | 试一试: 131 | 132 | ```py 133 | print( list(enumerate("hello", start=2)) ) 134 | 135 | for index, value in enumerate("hello", start=2): 136 | print(index, value) 137 | ``` 138 | 139 | * * * 140 | 141 | * * * -------------------------------------------------------------------------------- /docs/44.md: -------------------------------------------------------------------------------- 1 | # Python `reversed()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/reversed/](https://thepythonguru.com/python-builtin-functions/reversed/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `reversed()`函数允许我们以相反的顺序处理项目。 它接受一个序列并返回一个迭代器。 12 | 13 | 其语法如下: 14 | 15 | **语法**: 16 | 17 | ```py 18 | reversed(sequence) -> reverse iterator 19 | 20 | ``` 21 | 22 | | 参数 | 描述 | 23 | | --- | --- | 24 | | `sequence` | 序列列表字符串,列表,元组等。 | 25 | 26 | 这里有些例子: 27 | 28 | ```py 29 | >>> 30 | >>> reversed([44, 11, -90, 55, 3]) 31 | 32 | >>> 33 | >>> 34 | >>> list(reversed([44, 11, -90, 55, 3])) # reversing a list 35 | [3, 55, -90, 11, 44] 36 | >>> 37 | >>> 38 | >>> list(reversed((6, 1, 3, 9))) # reversing a tuple 39 | [9, 3, 1, 6] 40 | >>> 41 | >>> list(reversed("hello")) # reversing a string 42 | ['o', 'l', 'l', 'e', 'h'] 43 | >>> 44 | 45 | ``` 46 | 47 | 试试看: 48 | 49 | ```py 50 | print( reversed([44, 11, -90, 55, 3]) ) 51 | 52 | print(list(reversed([44, 11, -90, 55, 3]))) # reversing a list 53 | 54 | print( list(reversed((6, 1, 3, 9)))) # reversing a tuple 55 | 56 | print(list(reversed("hello"))) # reversing a string 57 | ``` 58 | 59 | 为了立即产生结果,我们将`reversed()`包装在`list()`调用中。 Python 2 和 Python 3 都需要这样做。 60 | 61 | 传递给`reversed()`的参数必须是正确的序列。 尝试传递不保持其顺序(例如`dict`和`set`)的对象将导致`TypeError`。 62 | 63 | ```py 64 | >>> 65 | >>> reversed({0, 4, -2, 12, 6}) 66 | Traceback (most recent call last): 67 | File "", line 1, in 68 | TypeError: argument to reversed() must be a sequence 69 | >>> 70 | >>> 71 | >>> reversed({'name': 'John', 'age': 20}) 72 | Traceback (most recent call last): 73 | File "", line 1, in 74 | TypeError: argument to reversed() must be a sequence 75 | >>> 76 | 77 | ``` 78 | 79 | ## 反转用户定义的对象 80 | 81 | * * * 82 | 83 | 若要反转用户定义的对象,该类必须执行下列操作之一: 84 | 85 | 1. 实现`__len__()`和`__getitem__()`方法; 要么 86 | 2. 实现`__reversed__()`方法 87 | 88 | 在下面的清单中,`CardDeck`类实现`__len__()`和`__getitem__()`方法。 结果,我们可以将`reversed()`应用于`CardDeck`实例。 89 | 90 | ```py 91 | >>> 92 | >>> from collections import namedtuple 93 | >>> 94 | >>> Card = namedtuple('Card', ['rank', 'suit']) 95 | >>> 96 | >>> class CardDeck: 97 | ... suits = ('club', 'diamond', 'heart', 'spades') 98 | ... ranks = tuple((str(i) for i in range(2, 11))) + tuple("JQKA") 99 | ... 100 | ... def __init__(self): 101 | ... self._cards = [Card(r, s) for s in self.suits for r in self.ranks ] 102 | ... 103 | ... def __len__(self): 104 | ... return len(self._cards) 105 | ... 106 | ... def __getitem__(self, index): 107 | ... return self._cards[index] 108 | ... 109 | ... # def __reversed__(self): this is how you would define __reversed__() method 110 | ... # return self._cards[::-1] 111 | ... 112 | ... 113 | >>> 114 | >>> deck = CardDeck() 115 | >>> 116 | >>> deck 117 | <__main__.CardDeck object at 0x7f2aff2feb00> 118 | >>> 119 | >>> 120 | >>> deck[0], deck[-1] # deck before reversing 121 | (Card(rank='2', suit='club'), Card(rank='A', suit='spades')) 122 | >>> 123 | >>> 124 | >>> reversed_deck = list(reversed(deck)) 125 | >>> 126 | >>> 127 | >>> reversed_deck[0], reversed_deck[-1] # deck after reversing 128 | (Card(rank='A', suit='spades'), Card(rank='2', suit='club')) 129 | >>> 130 | 131 | ``` 132 | 133 | 试一试: 134 | 135 | ```py 136 | from collections import namedtuple 137 | 138 | Card = namedtuple('Card', ['rank', 'suit']) 139 | 140 | class CardDeck: 141 | suits = ('club', 'diamond', 'heart', 'spades') 142 | ranks = tuple((str(i) for i in range(2, 11))) + tuple("JQKA") 143 | 144 | def __init__(self): 145 | self._cards = [Card(r, s) for s in self.suits for r in self.ranks ] 146 | 147 | def __len__(self): 148 | return len(self._cards) 149 | 150 | def __getitem__(self, index): 151 | return self._cards[index] 152 | 153 | # def __reversed__(self): this is how you would define __reversed__() method 154 | # return self._cards[::-1] 155 | 156 | deck = CardDeck() 157 | 158 | print(deck) 159 | 160 | print( deck[0], deck[-1] ) # deck before reversing 161 | 162 | reversed_deck = list(reversed(deck)) 163 | 164 | print(reversed_deck[0], reversed_deck[-1] ) # deck after reversing 165 | ``` 166 | 167 | * * * 168 | 169 | * * * -------------------------------------------------------------------------------- /docs/45.md: -------------------------------------------------------------------------------- 1 | # Python `range()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/range/](https://thepythonguru.com/python-builtin-functions/range/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `range()`函数用于随时间生成一系列数字。 简单地说,它接受一个整数并返回一个范围对象(一种可迭代的类型)。 在 Python 2 中,`range()`返回一个`list`,它对处理大数据不是很有效。 12 | 13 | `range()`函数的语法如下: 14 | 15 | **语法**: 16 | 17 | ```py 18 | range([start,] stop [, step]) -> range object 19 | 20 | ``` 21 | 22 | | 参数 | 描述 | 23 | | --- | --- | 24 | | `start` | (可选)序列的起点。 默认为`0`。 | 25 | | `stop`(必填) | 序列的端点。 该项目将不包括在序列中。 | 26 | | `step`(可选) | 序列的步长。 默认为`1`。 | 27 | 28 | 现在让我们看几个示例,以了解`range()`的工作方式: 29 | 30 | **示例 1**: 31 | 32 | ```py 33 | >>> 34 | >>> range(5) 35 | range(0, 5) 36 | >>> 37 | >>> list(range(5)) # list() call is not required in Python 2 38 | [0, 1, 2, 3, 4] 39 | >>> 40 | 41 | ``` 42 | 43 | 试试看: 44 | 45 | ```py 46 | print(range(5)) 47 | 48 | # list() call is not required in Python 2 49 | print(list(range(5))) 50 | ``` 51 | 52 | 当使用单个参数调用`range()`时,它将生成从`0`到指定参数(但不包括它)的数字序列。 因此,序列中不包含数字`5`。 53 | 54 | **示例 2**: 55 | 56 | ```py 57 | >>> 58 | >>> range(5, 10) 59 | range(5, 10) 60 | >>> 61 | >>> list(range(5, 10)) 62 | [5, 6, 7, 8, 9] 63 | >>> 64 | 65 | ``` 66 | 67 | 试一试: 68 | 69 | ```py 70 | print(range(5, 10)) 71 | 72 | print(list(range(5, 10))) 73 | ``` 74 | 75 | 在这里`range()`用两个参数`5`和`10`调用。 结果,它将生成从`5`到`10`(但不包括`10`)的数字序列。 76 | 77 | 您还可以指定负数: 78 | 79 | ```py 80 | >>> 81 | >>> list(range(-2, 2)) 82 | [-2, -1, 0, 1] 83 | >>> 84 | >>> list(range(-100, -95)) 85 | [-100, -99, -98, -97, -96] 86 | >>> 87 | 88 | ``` 89 | 90 | 试一试: 91 | 92 | ```py 93 | print(list(range(-2, 2))) 94 | 95 | print(list(range(-100, -95))) 96 | ``` 97 | 98 | **示例 3**: 99 | 100 | ```py 101 | >>> 102 | >>> range(1, 20, 3) 103 | range(1, 20, 3) 104 | >>> 105 | >>> 106 | >>> list(range(1, 20, 3)) 107 | [1, 4, 7, 10, 13, 16, 19] 108 | >>> 109 | 110 | ``` 111 | 112 | 试一试: 113 | 114 | ```py 115 | print( range(1, 20, 3)) 116 | 117 | print(list(range(1, 20, 3))) 118 | ``` 119 | 120 | 在这里`range()`函数被`3`的`step`参数调用,因此它将每隔三个元素从`1`返回到`20`(当然不包括`20`)。 121 | 122 | 您也可以使用步骤参数来倒数。 123 | 124 | ```py 125 | >>> 126 | >>> list(range(20, 10, -1)) 127 | [20, 19, 18, 17, 16, 15, 14, 13, 12, 11] 128 | >>> 129 | >>> list(range(20, 10, -5)) 130 | [20, 15] 131 | >>> 132 | 133 | ``` 134 | 135 | 试一试: 136 | 137 | ```py 138 | print(list(range(20, 10, -1))) 139 | 140 | print(list(range(20, 10, -5))) 141 | ``` 142 | 143 | `range()`函数通常与`for`循环一起使用以重复执行一定次数的操作。 例如,在下面的清单中,我们使用`range()`执行循环主体 5 次。 144 | 145 | ```py 146 | >>> 147 | >>> for i in range(5): 148 | ... print(i) 149 | ... 150 | 0 151 | 1 152 | 2 153 | 3 154 | 4 155 | >>> 156 | 157 | ``` 158 | 159 | 试一试: 160 | 161 | ```py 162 | for i in range(5): 163 | print(i) 164 | ``` 165 | 166 | 该代码在功能上等同于以下代码: 167 | 168 | ```py 169 | >>> 170 | >>> for i in [0, 1, 2, 3, 4]: 171 | ... print(i) 172 | ... 173 | 0 174 | 1 175 | 2 176 | 3 177 | 4 178 | >>> 179 | 180 | ``` 181 | 182 | 但是,在实际代码中,应始终使用`range()`,因为它简洁,灵活且性能更好。 183 | 184 | * * * 185 | 186 | * * * -------------------------------------------------------------------------------- /docs/46.md: -------------------------------------------------------------------------------- 1 | # Python `sum()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/sum/](https://thepythonguru.com/python-builtin-functions/sum/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `sum()`函数采用一个可迭代的并返回其中的项目总数。 12 | 13 | **语法**: 14 | 15 | ```py 16 | sum(iterable, [start]) -> number 17 | 18 | ``` 19 | 20 | | 参数 | 描述 | 21 | | --- | --- | 22 | | `iterable`(必填) | 可迭代项,例如字符串,列表,字典等。 | 23 | | `start`(可选) | 一个可选的数值添加到最终结果中。 默认为`0`。 | 24 | 25 | `sum()`函数仅适用于数字值,尝试将其用于非数字类型将导致错误。 26 | 27 | 这是一个例子: 28 | 29 | ```py 30 | >>> 31 | >>> sum([1, 2, 3, 4, 5]) # sum values in a list 32 | 15 33 | >>> 34 | >>> sum((1, 2, 3, 4, 5)) # sum values in a tuple 35 | 15 36 | >>> 37 | >>> sum({1, 2, 3, 4, 5}) # sum values in a set 38 | 15 39 | >>> 40 | >>> sum({1: "one", 2: "two", 3: "three"}) # sum values in a 41 | 6 42 | >>> 43 | 44 | ``` 45 | 46 | 试试看: 47 | 48 | ```py 49 | print(sum([1, 2, 3, 4, 5])) # sum values in a list 50 | 51 | print(sum((1, 2, 3, 4, 5))) # sum values in a tuple 52 | 53 | print(sum({1, 2, 3, 4, 5})) # sum values in a set 54 | 55 | print(sum({1: "one", 2: "two", 3: "three"})) # sum values in a 56 | ``` 57 | 58 | 在最后一个命令中,`sum()`将字典中的键添加进去,而忽略其值。 59 | 60 | 这是另一个示例,它指定要添加到最终结果中的`start`值。 61 | 62 | ```py 63 | >>> 64 | >>> sum([10, 20, 30], 100) 65 | 160 66 | >>> 67 | 68 | ``` 69 | 70 | 试一试: 71 | 72 | ```py 73 | print(sum([10, 20, 30], 100)) 74 | ``` 75 | 76 | * * * 77 | 78 | * * * -------------------------------------------------------------------------------- /docs/47.md: -------------------------------------------------------------------------------- 1 | # Python `max()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/max/](https://thepythonguru.com/python-builtin-functions/max/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `max()`函数返回最大的输入值。 12 | 13 | 其语法如下: 14 | 15 | ```py 16 | max(iterable[, default=obj, key=func]) -> value 17 | 18 | ``` 19 | 20 | | 参数 | 描述 | 21 | | --- | --- | 22 | | `iterable`(必填) | 可迭代对象,例如字符串,列表,元组等。 | 23 | | `default`(可选) | 如果可迭代对象为空,则返回默认值。 | 24 | | `key`(可选) | 它引用单个参数函数以自定义排序顺序。 该函数应用于迭代器上的每个项目。 | 25 | 26 | 要么 27 | 28 | ```py 29 | max(a,b,c, ...[, key=func]) -> value 30 | 31 | ``` 32 | 33 | | 参数 | 描述 | 34 | | --- | --- | 35 | | `a, b, c ...` | 比较项目 | 36 | | `key`(可选) | 它引用单个参数函数以自定义排序顺序。 该函数应用于迭代器上的每个项目。 | 37 | 38 | 如果以可迭代方式调用`max()`,它将返回其中的最大项。 如果可迭代对象为空,则返回`default`值,否则引发`ValueError`异常。 39 | 40 | 如果使用多个参数调用`max()`,它将返回最大的参数。 41 | 42 | 让我们看一些例子: 43 | 44 | **示例 1** :以可迭代方式调用`max()` 45 | 46 | ```py 47 | >>> 48 | >>> max("abcDEF") # find largest item in the string 49 | 'c' 50 | >>> 51 | >>> 52 | >>> max([2, 1, 4, 3]) # find largest item in the list 53 | 4 54 | >>> 55 | >>> 56 | >>> max(("one", "two", "three")) # find largest item in the tuple 57 | 'two' 58 | >>> 59 | >>> 60 | >>> max({1: "one", 2: "two", 3: "three"}) # find largest item in the dict 61 | 3 62 | >>> 63 | >>> 64 | >>> max([]) # empty iterable causes ValueError 65 | Traceback (most recent call last): 66 | File "", line 1, in 67 | ValueError: max() arg is an empty sequence 68 | >>> 69 | >>> 70 | >>> max([], default=0) # supressing the error with default value 71 | 0 72 | >>> 73 | 74 | ``` 75 | 76 | 试试看: 77 | 78 | ```py 79 | # find largest item in the string 80 | print(max("abcDEF")) 81 | 82 | # find largest item in the list 83 | print(max([2, 1, 4, 3])) 84 | 85 | # find largest item in the tuple 86 | print(max(("one", "two", "three"))) 87 | 'two' 88 | 89 | # find largest item in the dict 90 | print(max({1: "one", 2: "two", 3: "three"})) 91 | 3 92 | 93 | # empty iterable causes ValueError 94 | # print(max([])) 95 | 96 | # supressing the error with default value 97 | print(max([], default=0)) 98 | ``` 99 | 100 | **示例 2** :使用多个参数调用`max()` 101 | 102 | ```py 103 | >>> 104 | >>> max(20, 10, 30, -5) 105 | 30 106 | >>> 107 | >>> 108 | >>> max("c", "b", "a", "Y", "Z") 109 | 'c' 110 | >>> 111 | >>> 112 | >>> max(3.14, -9.91, 2.41) 113 | 3.14 114 | >>> 115 | 116 | ``` 117 | 118 | 试图在不同类型的对象中找到最大值会导致错误。 119 | 120 | ```py 121 | >>> 122 | >>> max(10, "pypi") 123 | Traceback (most recent call last): 124 | File "", line 1, in 125 | TypeError: unorderable types: str() > int() 126 | >>> 127 | >>> 128 | >>> max(5, [-10, 55]) 129 | Traceback (most recent call last): 130 | File "", line 1, in 131 | TypeError: unorderable types: list() > int() 132 | >>> 133 | 134 | ``` 135 | 136 | ## 自定义排序顺序 137 | 138 | * * * 139 | 140 | 为了自定义排序顺序,我们使用`key`命名参数。 它的工作原理类似于 [sorted()](/python-builtin-functions/sorted/)函数的`key`命名参数。 141 | 142 | 这是一个使用键参数使字符串比较区分大小写的示例。 143 | 144 | ```py 145 | >>> 146 | >>> max("c", "b", "a", "Y", "Z") 147 | 'c' 148 | >>> 149 | >>> max("c", "b", "a", "Y", "Z", key=str.lower) 150 | 'Z' 151 | >>> 152 | 153 | ``` 154 | 155 | 试一试: 156 | 157 | ```py 158 | print(max("c", "b", "a", "Y", "Z")) 159 | 160 | print(max("c", "b", "a", "Y", "Z", key=str.lower)) 161 | ``` 162 | 163 | 以下是另一个示例,其中我们根据字符串的长度而不是其 ASCII 值比较字符串。 164 | 165 | ```py 166 | >>> 167 | >>> max(("python", "lua", "ruby")) 168 | 'ruby' 169 | >>> 170 | >>> 171 | >>> max(("python", "lua", "ruby"), key=len) 172 | 'python' 173 | >>> 174 | 175 | ``` 176 | 177 | 试一试: 178 | 179 | ```py 180 | print(max(("python", "lua", "ruby"))) 181 | 182 | print(max(("python", "lua", "ruby"), key=len)) 183 | ``` 184 | 185 | 还存在一个名为[`min()`](/python-builtin-functions/min/)的互补函数,该函数查找最低的输入值。 186 | 187 | * * * 188 | 189 | * * * -------------------------------------------------------------------------------- /docs/48.md: -------------------------------------------------------------------------------- 1 | # Python `min()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/min/](https://thepythonguru.com/python-builtin-functions/min/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `min()`函数返回最小的输入值。 12 | 13 | 其语法如下: 14 | 15 | ```py 16 | min(iterable[, default=obj, key=func]) -> value 17 | 18 | ``` 19 | 20 | | 参数 | 描述 | 21 | | --- | --- | 22 | | `iterable`(必填) | 可迭代对象,例如字符串,列表,元组等。 | 23 | | `default`(可选) | 如果可迭代对象为空,则返回默认值。 | 24 | | `key`(可选) | 它引用单个参数函数以自定义排序顺序。 该函数应用于迭代器上的每个项目。 | 25 | 26 | 要么 27 | 28 | ```py 29 | min(a, b, c, ...[, key=func]) -> value 30 | 31 | ``` 32 | 33 | | 参数 | 描述 | 34 | | --- | --- | 35 | | `a, b, c ...` | 比较项目 | 36 | | `key`(可选) | 它引用单个参数函数以自定义排序顺序。 该函数适用​​于每个项目。 | 37 | 38 | 如果以可迭代方式调用`min()`,它将返回其中的最小项。 如果可迭代对象为空,则返回`default`值(假设已提供),否则引发`ValueError`异常。 39 | 40 | 如果使用多个参数调用`min()`,它将返回最小的参数。 41 | 42 | 让我们看一些例子: 43 | 44 | **示例 1** :以可迭代方式调用`min()` 45 | 46 | ```py 47 | >>> 48 | >>> min("abcDEF") # find smallest item in the string 49 | 'D' 50 | >>> 51 | >>> 52 | >>> min([2, -1, 4, 3]) # find smallest item in the list 53 | -1 54 | >>> 55 | >>> 56 | >>> min(("one", "two", "three")) # find smallest item in the tuple 57 | 'one' 58 | >>> 59 | >>> 60 | >>> min({1: "one", 2: "two", 3: "three"}) # find smallest item in the dict 61 | 1 62 | >>> 63 | >>> 64 | >>> min([]) # empty iterable causes ValueError 65 | Traceback (most recent call last): 66 | File "", line 1, in 67 | ValueError: min() arg is an empty sequence 68 | >>> 69 | >>> 70 | >>> min([], default=0) # supressing the error with default value 71 | 0 72 | >>> 73 | 74 | ``` 75 | 76 | 试试看: 77 | 78 | ```py 79 | # find smallest item in the string 80 | print(min("abcDEF")) 81 | 82 | # find smallest item in the list 83 | print(min([2, -1, 4, 3])) 84 | 85 | # find smallest item in the tuple 86 | print(min(("one", "two", "three"))) 87 | 88 | # find smallest item in the dict 89 | print(min({1: "one", 2: "two", 3: "three"})) 90 | 91 | #print(min([])) # empty iterable causes ValueError 92 | 93 | # supressing the error with default value 94 | print(min([], default=0)) 95 | ``` 96 | 97 | **示例 2** :使用多个参数调用`min()` 98 | 99 | ```py 100 | >>> 101 | >>> min(20, 10, 30, -5) 102 | -5 103 | >>> 104 | >>> 105 | >>> min("c", "b", "a", "Y", "Z") 106 | 'Y' 107 | >>> 108 | >>> 109 | >>> min(3.14, -9.91, 2.41) 110 | -9.91 111 | >>> 112 | 113 | ``` 114 | 115 | 试一试: 116 | 117 | ```py 118 | print(min(20, 10, 30, -5)) 119 | 120 | print(min("c", "b", "a", "Y", "Z")) 121 | 122 | print(min(3.14, -9.91, 2.41)) 123 | ``` 124 | 125 | 试图在不同类型的对象中找到最大值会导致错误。 126 | 127 | ```py 128 | >>> 129 | >>> min(10, "pypi") 130 | Traceback (most recent call last): 131 | File "", line 1, in 132 | TypeError: unorderable types: str() > int() 133 | >>> 134 | >>> 135 | >>> min(5, [-10, 55]) 136 | Traceback (most recent call last): 137 | File "", line 1, in 138 | TypeError: unorderable types: list() > int() 139 | >>> 140 | 141 | ``` 142 | 143 | ## 自定义排序顺序 144 | 145 | * * * 146 | 147 | 为了自定义排序顺序,我们使用`key`命名参数。 它的工作原理类似于[`sorted()`](/python-builtin-functions/sorted/)函数的`key`命名参数。 148 | 149 | 这是一个使用键参数使字符串比较区分大小写的示例。 150 | 151 | ```py 152 | >>> 153 | >>> min("c", "b", "a", "Y", "Z") 154 | 'Y' 155 | >>> 156 | >>> min("c", "b", "a", "Y", "Z", key=str.lower) 157 | 'a' 158 | >>> 159 | 160 | ``` 161 | 162 | 试一试: 163 | 164 | ```py 165 | print(min("c", "b", "a", "Y", "Z")) 166 | 167 | print(min("c", "b", "a", "Y", "Z", key=str.lower)) 168 | ``` 169 | 170 | 以下是另一个示例,其中我们根据字符串的长度而不是其 ASCII 值比较字符串。 171 | 172 | ```py 173 | >>> 174 | >>> min(("java", "python", "z++")) 175 | 'java' 176 | >>> 177 | >>> min(("java", "python", "z++"), key=len) 178 | 'z++' 179 | >>> 180 | 181 | ``` 182 | 183 | 试一试: 184 | 185 | ```py 186 | print(min(("java", "python", "z++"))) 187 | 188 | print(min(("java", "python", "z++"), key=len)) 189 | ``` 190 | 191 | 还存在一个互补函数,称为[`max()`](/python-builtin-functions/max/),可找到最大的输入值。 192 | 193 | * * * 194 | 195 | * * * -------------------------------------------------------------------------------- /docs/49.md: -------------------------------------------------------------------------------- 1 | # Python `eval()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/eval/](https://thepythonguru.com/python-builtin-functions/eval/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `eval()`允许我们执行任意字符串作为 Python 代码。 它接受源字符串并返回一个对象。 12 | 13 | 其语法如下: 14 | 15 | **语法**: 16 | 17 | ```py 18 | eval(expr, globals=None, locals=None) 19 | 20 | ``` 21 | 22 | | 参数 | 描述 | 23 | | --- | --- | 24 | | `expr`(必填) | `expr`可以是任何有效的 Python 表达式 | 25 | | `globals`(可选) | 执行源时要使用的全局名称空间。 它必须是字典。 如果未提供,则将使用当前的全局名称空间。 | 26 | | `locals`(可选) | 执行源时要使用的本地名称空间。 它可以是任何映射。 如果省略,则默认为`globals`字典。 | 27 | 28 | 如果同时省略`globals`和`locals`,则使用当前的全局和局部名称空间。 29 | 30 | 这是一个演示`eval()`如何工作的示例: 31 | 32 | ```py 33 | >>> 34 | >>> eval("5 == 5") 35 | True 36 | >>> 37 | >>> 38 | >>> eval("4 < 10") 39 | True 40 | >>> 41 | >>> 42 | >>> eval("8 + 4 - 2 * 3") 43 | 6 44 | >>> 45 | >>> 46 | >>> eval("'py ' * 5") 47 | 'py py py py py ' 48 | >>> 49 | >>> 50 | >>> eval("10 ** 2") 51 | 100 52 | >>> 53 | >>> 54 | >>> eval("'hello' + 'py'") 55 | 'hellopy' 56 | >>> 57 | 58 | ``` 59 | 60 | 试试看: 61 | 62 | ```py 63 | print(eval("5 == 5")) 64 | 65 | print(eval("4 < 10")) 66 | 67 | print(eval("8 + 4 - 2 * 3")) 68 | 69 | print(eval("'py ' * 5")) 70 | 71 | print(eval("10 ** 2")) 72 | 73 | print(eval("'hello' + 'py'")) 74 | ``` 75 | 76 | `eval()`不仅限于简单表达。 我们可以执行函数,调用方法,引用变量等。 77 | 78 | ```py 79 | >>> 80 | >>> eval("abs(-11)") 81 | 11 82 | >>> 83 | >>> 84 | >>> eval('"hello".upper()') 85 | 'HELLO' 86 | >>> 87 | >>> 88 | >>> import os 89 | >>> 90 | >>> 91 | >>> eval('os.getcwd()') # get current working directory 92 | '/home/thepythonguru' 93 | >>> 94 | >>> 95 | >>> x = 2 96 | >>> 97 | >>> eval("x+4") # x is referenced inside the expression 98 | 6 99 | >>> 100 | 101 | ``` 102 | 103 | 试一试: 104 | 105 | ```py 106 | print(eval("abs(-11)")) 107 | 108 | print(eval('"hello".upper()')) 109 | 110 | import os 111 | 112 | # get current working directory 113 | print(eval('os.getcwd()')) 114 | 115 | x = 2 116 | 117 | print(eval("x+4")) # x is referenced inside the expression 118 | ``` 119 | 120 | 请注意,`eval()`仅适用于表达式。 尝试传递语句会导致`SyntaxError`。 121 | 122 | ```py 123 | >>> 124 | >>> eval('a=1') # assignment statement 125 | Traceback (most recent call last): 126 | File "", line 1, in 127 | File "", line 1 128 | a=1 129 | ^ 130 | SyntaxError: invalid syntax 131 | >>> 132 | >>> 133 | >>> eval('import re') # import statement 134 | Traceback (most recent call last): 135 | File "", line 1, in 136 | File "", line 1 137 | import re 138 | ^ 139 | SyntaxError: invalid syntax 140 | >>> 141 | 142 | ``` 143 | 144 | ## 邪恶的`eval()` 145 | 146 | * * * 147 | 148 | 您永远不要直接将不受信任的源传递给`eval()`。 由于恶意用户很容易对您的系统造成破坏。 例如,以下代码可以用于从系统中删除所有文件。 149 | 150 | ```py 151 | >>> 152 | eval('os.system("RM -RF /")') # command is deliberately capitalized 153 | >>> 154 | 155 | ``` 156 | 157 | 如果`os`模块在您当前的全局范围内不可用,则以上代码将失败。 但是我们可以通过使用`__import__()`内置函数轻松地避免这种情况。 158 | 159 | ```py 160 | >>> 161 | >>> eval("__import__('os').system('RM -RF /')") # command is deliberately capitalized 162 | >>> 163 | 164 | ``` 165 | 166 | 那么有什么方法可以使`eval()`安全吗? 167 | 168 | ## 指定命名空间 169 | 170 | * * * 171 | 172 | `eval()`可选地接受两个映射,作为要执行的表达式的全局和局部名称空间。 如果未提供映射,则将使用全局和局部名称空间的当前值。 173 | 174 | 这里有些例子: 175 | 176 | **示例 1**: 177 | 178 | ```py 179 | >>> 180 | >>> globals = { 181 | ... 'a': 10, 182 | ... 'fruits': ['mangoes', 'peaches', 'bananas'], 183 | ... } 184 | >>> 185 | >>> 186 | >>> locals = {} 187 | >>> 188 | >>> 189 | >>> eval("str(a) + ' ' + fruits[0]", globals, locals) 190 | '10 mangoes' 191 | >>> 192 | 193 | ``` 194 | 195 | **示例 2**: 196 | 197 | ```py 198 | >>> 199 | >>> eval('abs(-100)', {}, {}) 200 | 100 201 | >>> 202 | 203 | ``` 204 | 205 | 即使我们已经将空字典作为全局和本地名称空间传递了,`eval()`仍可以访问内置函数(即`__builtins__`)。 206 | 207 | ```py 208 | >>> 209 | >>> dir(__builtins__) 210 | ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 211 | ... 212 | ... 213 | 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted' 214 | , 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] 215 | >>> 216 | 217 | ``` 218 | 219 | 要从全局名称空间中删除内置函数,请传递一个字典,该字典包含一个值为`None`的键`__builtins__`。 220 | 221 | **示例 3**: 222 | 223 | ```py 224 | >>> 225 | >>> eval('abs(-100)', {'__builtins__':None}, {}) 226 | Traceback (most recent call last): 227 | File "", line 1, in 228 | File "", line 1, in 229 | TypeError: 'NoneType' object is not subscriptable 230 | >>> 231 | 232 | ``` 233 | 234 | 即使删除对内置函数的访问权限后,`eval()`仍然不安全。 考虑以下清单。 235 | 236 | ```py 237 | >>> 238 | >>> eval("5**98765432111123", {'__builtins__':None}, {}) 239 | >>> 240 | 241 | ``` 242 | 243 | 这个看似简单的外观表达式足以使您的 CPU 崩溃。 244 | 245 | 关键要点是仅将`eval()`与受信任的源一起使用。 246 | 247 | * * * 248 | 249 | * * * -------------------------------------------------------------------------------- /docs/5.md: -------------------------------------------------------------------------------- 1 | # 运行 python 程序 2 | 3 | > 原文: [https://thepythonguru.com/running-python-programs/](https://thepythonguru.com/running-python-programs/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | 您可以通过两种方式运行 python 程序,首先通过直接在 python shell 中键入命令或运行存储在文件中的程序。 但是大多数时候您想运行存储在文件中的程序。 12 | 13 | 让我们在记事本目录中创建一个名为`hello.py`的文件,即使用记事本(或您选择的任何其他文本编辑器)创建一个`C:\Users\YourUserName\Documents`,记住 python 文件具有`.py`扩展名,然后在文件中编写以下代码。 14 | 15 | ```py 16 | print("Hello World") 17 | 18 | ``` 19 | 20 | 在 python 中,我们使用`print`函数将字符串显示到控制台。 它可以接受多个参数。 当传递两个或多个参数时,`print()`函数显示每个参数,并用空格分隔。 21 | 22 | ```py 23 | print("Hello", "World") 24 | 25 | ``` 26 | 27 | **预期输出**: 28 | 29 | ```py 30 | Hello World 31 | 32 | ``` 33 | 34 | 现在打开终端,并使用`cd`命令将当前工作目录更改为`C:\Users\YourUserName\Documents`。 35 | 36 | ![CHANGE-CURRENT-WORKING-DIRECTORY.png](img/a221810ac323791d4ac671449aa078e1.png) 37 | 38 | 要运行该程序,请键入以下命令。 39 | 40 | ```py 41 | python hello.py 42 | 43 | ``` 44 | 45 | ![RUNNING-HELLO-WORLD-PROGRAM.png](img/6113451b01106e8adff5df5b50e8d069.png) 46 | 47 | 如果一切顺利,您将获得以下输出。 48 | 49 | ```py 50 | Hello World 51 | 52 | ``` 53 | 54 | ## 获得帮助 55 | 56 | * * * 57 | 58 | 使用 python 迟早会遇到一种情况,您想了解更多有关某些方法或函数的信息。 为了帮助您,Python 具有`help()`函数,这是如何使用它。 59 | 60 | **语法**: 61 | 62 | 要查找有关类别的信息:`help(class_name)` 63 | 64 | 要查找有关方法的更多信息,属于类别:`help(class_name.method_name)` 65 | 66 | 假设您想了解更多关于`int`类的信息,请转到 Python shell 并键入以下命令。 67 | 68 | ```py 69 | >>> help(int) 70 | 71 | Help on class int in module builtins: 72 | 73 | class int(object) 74 | | int(x=0) -> integer 75 | | int(x, base=10) -> integer 76 | | 77 | | Convert a number or string to an integer, or return 0 if no arguments 78 | | are given. If x is a number, return x.__int__(). For floating point 79 | | numbers, this truncates towards zero. 80 | | 81 | | If x is not a number or if base is given, then x must be a string, 82 | | bytes, or bytearray instance representing an integer literal in the 83 | | given base. The literal can be preceded by '+' or '-' and be surrounded 84 | | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. 85 | | Base 0 means to interpret the base from the string as an integer literal. 86 | | >>> int('0b100', base=0) 87 | | 4 88 | | 89 | | Methods defined here: 90 | | 91 | | __abs__(self, /) 92 | | abs(self) 93 | | 94 | | __add__(self, value, /) 95 | | Return self+value. 96 | 97 | ``` 98 | 99 | 如您所见,`help()`函数使用所有方法吐出整个`int`类,它还在需要的地方包含说明。 100 | 101 | 现在,假设您想知道`str`类的`index()`方法所需的参数,要找出您需要在 python shell 中键入以下命令。 102 | 103 | ```py 104 | >>> help(str.index) 105 | 106 | Help on method_descriptor: 107 | 108 | index(...) 109 | S.index(sub[, start[, end]]) -> int 110 | 111 | Like S.find() but raise ValueError when the substring is not found. 112 | 113 | ``` 114 | 115 | 在下一篇文章中,我们将学习 python 中的数据类型和变量。 116 | 117 | * * * 118 | 119 | * * * -------------------------------------------------------------------------------- /docs/50.md: -------------------------------------------------------------------------------- 1 | # Python `len()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/len/](https://thepythonguru.com/python-builtin-functions/len/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `len()`函数计算对象中的项目数。 12 | 13 | 其语法如下: 14 | 15 | ```py 16 | len(obj) -> length 17 | 18 | ``` 19 | 20 | | 参数 | 描述 | 21 | | --- | --- | 22 | | `obj` | `obj`可以是字符串,列表,字典,元组等。 | 23 | 24 | 这是一个例子: 25 | 26 | ```py 27 | >>> 28 | >>> len([1, 2, 3, 4, 5]) # length of list 29 | 5 30 | >>> 31 | >>> print(len({"spande", "club", "diamond", "heart"})) # length of set 32 | 4 33 | >>> 34 | >>> print(len(("alpha", "beta", "gamma"))) # length of tuple 35 | 3 36 | >>> 37 | >>> print(len({ "mango": 10, "apple": 40, "plum": 16 })) # length of dictionary 38 | 3 39 | 40 | ``` 41 | 42 | 试试看: 43 | 44 | ```py 45 | # length of list 46 | print(len([1, 2, 3, 4, 5])) 47 | 48 | # length of set 49 | print(len({"spande", "club", "diamond", "heart"})) 50 | 51 | # length of tuple 52 | print(len(("alpha", "beta", "gamma"))) 53 | 54 | # length of dictionary 55 | print(len({ "mango": 10, "apple": 40, "plum": 16 })) 56 | ``` 57 | 58 | 具有讽刺意味的是,`len()`函数不适用于生成器。 尝试在生成器对象上调用`len()`将导致`TypeError`异常。 59 | 60 | ```py 61 | >>> 62 | >>> def gen_func(): 63 | ... for i in range(5): 64 | ... yield i 65 | ... 66 | >>> 67 | >>> 68 | >>> len(gen_func()) 69 | Traceback (most recent call last): 70 | File "", line 1, in 71 | TypeError: object of type 'generator' has no len() 72 | >>> 73 | 74 | ``` 75 | 76 | 试一试: 77 | 78 | ```py 79 | def gen_func(): 80 | for i in range(5): 81 | yield i 82 | 83 | print(len(gen_func())) 84 | ``` 85 | 86 | ## `len()`与用户定义的对象 87 | 88 | * * * 89 | 90 | 要在用户定义的对象上使用`len()`,您将必须实现`__len__()`方法。 91 | 92 | ```py 93 | >>> 94 | >>> class Stack: 95 | ... 96 | ... def __init__(self): 97 | ... self._stack = [] 98 | ... 99 | ... def push(self, item): 100 | ... self._stack.append(item) 101 | ... 102 | ... def pop(self): 103 | ... self._stack.pop() 104 | ... 105 | ... def __len__(self): 106 | ... return len(self._stack) 107 | ... 108 | >>> 109 | >>> s = Stack() 110 | >>> 111 | >>> len(s) 112 | 0 113 | >>> 114 | >>> s.push(2) 115 | >>> s.push(5) 116 | >>> s.push(9) 117 | >>> s.push(12) 118 | >>> 119 | >>> len(s) 120 | 4 121 | >>> 122 | 123 | ``` 124 | 125 | 试一试: 126 | 127 | ```py 128 | class Stack: 129 | def __init__(self): 130 | self._stack = [] 131 | 132 | def push(self, item): 133 | self._stack.append(item) 134 | 135 | def pop(self): 136 | self._stack.pop() 137 | 138 | def __len__(self): 139 | return len(self._stack) 140 | 141 | s = Stack() 142 | 143 | print(len(s)) 144 | 145 | s.push(2) 146 | s.push(5) 147 | s.push(9) 148 | s.push(12) 149 | 150 | print(len(s)) 151 | ``` 152 | 153 | * * * 154 | 155 | * * * -------------------------------------------------------------------------------- /docs/51.md: -------------------------------------------------------------------------------- 1 | # Python `ord()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/ord/](https://thepythonguru.com/python-builtin-functions/ord/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `ord()`函数(缺少序数)返回一个整数,表示传递给它的字符。 对于 ASCII 字符,返回值是 7 位 ASCII 代码,对于 Unicode 字符,返回值是指 Unicode 代码点。 12 | 13 | 其语法如下: 14 | 15 | ```py 16 | ord(c) -> code point 17 | ``` 18 | 19 | | 参数 | 描述 | 20 | | --- | --- | 21 | | `c` | `c`是字符串字符串。 | 22 | 23 | 这是一个例子: 24 | 25 | ```py 26 | >>> 27 | >>> ord("A") 28 | 65 29 | >>> 30 | >>> 31 | >>> ord("f") 32 | 102 33 | >>> 34 | >>> 35 | >>> ord("á") # accented a 36 | 225 37 | >>> 38 | >>> 39 | >>> ord("卍") # swastika 40 | 21325 41 | >>> 42 | >>> 43 | >>> ord("😀") # Grinning Face 44 | 128512 45 | >>> 46 | 47 | ``` 48 | 49 | 试试看: 50 | 51 | ```py 52 | print(ord("A")) 53 | 54 | print(ord("f")) 55 | 56 | print(ord("á")) # accented a 57 | 58 | print(ord("卍")) # swastika 59 | 60 | print(ord("😀")) # Grinning Face 61 | ``` 62 | 63 | 要将`ord()`返回的整数转换回其等效字符,我们使用[`chr()`](/python-builtin-functions/chr/)函数。 64 | 65 | * * * 66 | 67 | * * * -------------------------------------------------------------------------------- /docs/52.md: -------------------------------------------------------------------------------- 1 | # Python `chr()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/chr/](https://thepythonguru.com/python-builtin-functions/chr/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `chr()`函数返回由整数序数值表示的单个字符串。 12 | 13 | 其语法如下: 14 | 15 | ```py 16 | chr(integer) -> single character string 17 | 18 | ``` 19 | 20 | 这是一个例子: 21 | 22 | ```py 23 | >>> 24 | >>> chr(65) 25 | 'A' 26 | >>> 27 | >>> 28 | >>> chr(102) 29 | 'f' 30 | >>> 31 | >>> 32 | >>> chr(225) # accented a 33 | 'á' 34 | >>> 35 | >>> 36 | >>> chr(21325) # swastika 37 | '卍' 38 | >>> 39 | >>> 40 | >>> chr(128512) # Grinning Face 41 | '😀' 42 | >>> 43 | 44 | ``` 45 | 46 | 试试看: 47 | 48 | ```py 49 | print(chr(65)) 50 | 51 | print(chr(102)) 52 | 53 | print(chr(225)) # accented a 54 | 55 | print(chr(21325)) # swastika 56 | 57 | print(chr(128512)) # Grinning Face 58 | ``` 59 | 60 | 要将字符转换回整数,请使用[`ord()`](/python-builtin-functions/ord/)函数。 61 | 62 | * * * 63 | 64 | * * * -------------------------------------------------------------------------------- /docs/53.md: -------------------------------------------------------------------------------- 1 | # Python `any()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/any/](https://thepythonguru.com/python-builtin-functions/any/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `any()`函数测试可迭代项中的任何项目是否求值为`True`。 它接受一个可迭代对象并返回`True`,如果可迭代对象中的至少一项为`true`,则返回`False`。 12 | 13 | 其语法如下: 14 | 15 | ```py 16 | any(iterable) -> boolean 17 | 18 | ``` 19 | 20 | 这是一个例子: 21 | 22 | ```py 23 | >>> 24 | >>> any([10, "", "one"]) 25 | True 26 | >>> 27 | >>> 28 | >>> any(("", {})) 29 | False 30 | >>> 31 | >>> 32 | >>> 33 | >>> any([]) 34 | False 35 | >>> 36 | >>> 37 | >>> gen = (i for i in [5, 0, 0.0, 4]) # generator 38 | >>> 39 | >>> any(gen) 40 | True 41 | >>> 42 | 43 | ``` 44 | 45 | 试试看: 46 | 47 | ```py 48 | print(any([10, "", "one"])) 49 | 50 | print(any(("", {}))) 51 | 52 | print(any([])) 53 | 54 | gen = (i for i in [5, 0, 0.0, 4]) # generator 55 | 56 | print(any(gen)) 57 | ``` 58 | 59 | * * * 60 | 61 | * * * -------------------------------------------------------------------------------- /docs/54.md: -------------------------------------------------------------------------------- 1 | # Python `all()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/all/](https://thepythonguru.com/python-builtin-functions/all/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `all()`函数测试可迭代项中的所有项目是否都等于`True`。 如果所有项目都为`true`,它将接受一个可迭代对象并返回`True`,否则返回`False`。 12 | 13 | 其语法如下: 14 | 15 | ```py 16 | all(iterable) -> boolean 17 | 18 | ``` 19 | 20 | 这是一个例子: 21 | 22 | ```py 23 | >>> 24 | >>> all(['alpha', 'beta', '']) 25 | False 26 | >>> 27 | >>> 28 | >>> all(['one', 'two', 'three']) 29 | True 30 | >>> 31 | >>> 32 | >>> all([]) 33 | True 34 | >>> 35 | >>> 36 | >>> gen = (i for i in ['0', (), {}, 51, 89]) # generator 37 | >>> 38 | >>> 39 | >>> all(gen) 40 | False 41 | >>> 42 | 43 | ``` 44 | 45 | 试试看: 46 | 47 | ```py 48 | print(all(['alpha', 'beta', ''])) 49 | 50 | print(all(['one', 'two', 'three'])) 51 | 52 | print(all([])) 53 | 54 | gen = (i for i in ['0', (), {}, 51, 89]) # generator 55 | 56 | print(all(gen)) 57 | ``` 58 | 59 | * * * 60 | 61 | * * * -------------------------------------------------------------------------------- /docs/55.md: -------------------------------------------------------------------------------- 1 | # Python `globals()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/globals/](https://thepythonguru.com/python-builtin-functions/globals/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `globals()`函数返回一个字典,其中包含在全局命名空间中定义的变量。 当从函数或方法中调用`globals()`时,它将返回表示该函数或方法所定义的模块的全局命名空间的字典,而不是从其调用处。 12 | 13 | 其语法如下: 14 | 15 | ```py 16 | globals() -> dictionary 17 | 18 | ``` 19 | 20 | 让我们举一些例子: 21 | 22 | **示例 1**: 23 | 24 | **`module1.py`** 25 | 26 | ```py 27 | #!/usr/bin/python3 28 | 29 | from pprint import pprint 30 | 31 | a = 100 32 | b = 4 33 | 34 | def foo(): 35 | x = 100 # x is a local variable 36 | 37 | pprint(globals()) 38 | 39 | ``` 40 | 41 | **预期输出**: 42 | 43 | ```py 44 | {'__builtins__': , 45 | '__cached__': None, 46 | '__doc__': None, 47 | '__file__': './module1.py', 48 | '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f699cab37f0>, 49 | '__name__': '__main__', 50 | '__package__': None, 51 | '__spec__': None, 52 | 'a': 100, 53 | 'b': 4, 54 | 'foo': , 55 | 'pprint': } 56 | 57 | ``` 58 | 59 | 试试看: 60 | 61 | ```py 62 | from pprint import pprint 63 | 64 | a = 100 65 | b = 4 66 | 67 | def foo(): 68 | x = 100 # x is a local variable 69 | 70 | pprint(globals()) 71 | ``` 72 | 73 | 以双下划线开头和结尾的名称是特殊的,并且由 Python 解释器定义。 我们在模块中定义的变量最后出现。 74 | 75 | 请注意,在`foo()`函数内部定义的局部变量`x`不包含在结果中。 要访问本地名称空间,请使用[`locals()`](/python-builtin-functions/locals/)函数。 76 | 77 | **示例 2**: 78 | 79 | **`module1.py`** 80 | 81 | ```py 82 | #!/usr/bin/python3 83 | 84 | from pprint import pprint 85 | 86 | a = 100 87 | b = 4 88 | 89 | def foo(): 90 | x = 100 # x is a local variable 91 | pprint(globals()) 92 | 93 | ``` 94 | 95 | **`module2.py`** 96 | 97 | ```py 98 | #!/usr/bin/python3 99 | 100 | import module1 101 | 102 | x = 100 103 | y = 2 104 | 105 | module1.foo() 106 | 107 | ``` 108 | 109 | **预期输出**: 110 | 111 | ```py 112 | {'__builtins__': { ... } 113 | '__cached__': '/home/overiq/tmp/__pycache__/module1.cpython-35.pyc', 114 | '__doc__': None, 115 | '__file__': '/home/overiq/tmp/module1.py', 116 | '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f17b12305c0>, 117 | '__name__': 'module1', 118 | '__package__': '', 119 | '__spec__': ModuleSpec(name='module1', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f17b12305c0>, origin='/home/overiq/tmp/module1.py'), 120 | 'a': 100, 121 | 'b': 4, 122 | 'foo': , 123 | 'pprint': } 124 | 125 | ``` 126 | 127 | 在这种情况下,`globals()`调用位于`foo()`函数内部。 当从`module2`调用`foo()`函数时,它将打印在`module1`的全局命名空间中定义的变量。 128 | 129 | * * * 130 | 131 | * * * -------------------------------------------------------------------------------- /docs/56.md: -------------------------------------------------------------------------------- 1 | # Python `locals()`函数 2 | 3 | > 原文: [https://thepythonguru.com/python-builtin-functions/locals/](https://thepythonguru.com/python-builtin-functions/locals/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | `locals()`函数返回一个字典,其中包含在本地名称空间中定义的变量。 在全局名称空间中调用`locals()`与调用[`globals()`](/python-builtin-functions/globals/)相同,并返回代表模块全局名称空间的字典。 12 | 13 | 其语法如下: 14 | 15 | ```py 16 | locals() -> dictionary containg local scope variables 17 | 18 | ``` 19 | 20 | 这是一个例子: 21 | 22 | ```py 23 | #!/usr/bin/python3 24 | 25 | from pprint import pprint 26 | 27 | a = 10 28 | b = 20 29 | 30 | def foo(): 31 | x = 30 # x and y are local variables 32 | y = 40 33 | 34 | print("locals() = {0}".format(locals())) 35 | 36 | pprint(locals()) # same as calling globals() 37 | 38 | print('*' * 80) 39 | 40 | print("locals() == globals()? ", locals() == globals()) 41 | 42 | print('*' * 80) 43 | 44 | foo() 45 | 46 | ``` 47 | 48 | **预期输出**: 49 | 50 | ```py 51 | {'__builtins__': , 52 | '__cached__': None, 53 | '__doc__': None, 54 | '__file__': 'module1.py', 55 | '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fa18790a828>, 56 | '__name__': '__main__', 57 | '__package__': None, 58 | '__spec__': None, 59 | 'a': 10, 60 | 'b': 20, 61 | 'foo': , 62 | 'pprint': } 63 | 64 | ******************************************************************************** 65 | 66 | locals() == globals()? True 67 | 68 | ******************************************************************************** 69 | 70 | locals() = {'y': 40, 'x': 30} 71 | 72 | ``` 73 | 74 | 试试看: 75 | 76 | ```py 77 | from pprint import pprint 78 | 79 | a = 10 80 | b = 20 81 | 82 | def foo(): 83 | x = 30 # x and y are local variables 84 | y = 40 85 | 86 | print("locals() = {0}".format(locals())) 87 | 88 | pprint(locals()) # same as calling globals() 89 | 90 | print('*' * 80) 91 | 92 | print("locals() == globals()? ", locals() == globals()) 93 | 94 | print('*' * 80) 95 | 96 | foo() 97 | ``` 98 | 99 | * * * 100 | 101 | * * * -------------------------------------------------------------------------------- /docs/57.md: -------------------------------------------------------------------------------- 1 | # 数据库访问 -------------------------------------------------------------------------------- /docs/58.md: -------------------------------------------------------------------------------- 1 | # 安装 Python MySQLdb 2 | 3 | > 原文: [https://thepythonguru.com/installing-mysqldb/](https://thepythonguru.com/installing-mysqldb/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | MySQLdb 是用于使用 python 访问 MySQL 数据库的 api。 它建立在 MySQL C API 之上。 12 | 13 | MySQLdb 尚不支持 python 3,它仅支持 python 2.4-2.7。 因此,您需要在本教程中使用 python 2。 我们将使用 python 2.7.9,您可以从此处下载。 14 | 15 | ## 安装 MySQLdb 16 | 17 | * * * 18 | 19 | 在安装之前,必须首先检查系统上是否已经安装了 MySQLdb。 要测试打开命令提示符或终端,然后启动 python shell 并键入以下代码 20 | 21 | ```py 22 | import MySQLdb 23 | 24 | ``` 25 | 26 | 如果它像这样抛出`ImportError`: 27 | 28 | ![check-mysqldb-installation.png](img/96a007840d513479e414cd40e5b67e2c.png) 29 | 30 | 那么您需要安装 MySQLdb。 否则,您已经安装了 MySQLdb。 31 | 32 | 如果您在 Windows 上,请[下载 MySQLdb 并安装它](http://sourceforge.net/projects/mysql-python/)。 33 | 34 | 在下一篇文章中,我们将讨论[如何连接到访问数据库](/connecting-to-the-database/)。 35 | 36 | * * * 37 | 38 | * * * -------------------------------------------------------------------------------- /docs/59.md: -------------------------------------------------------------------------------- 1 | # 连接到数据库 2 | 3 | > 原文: [https://thepythonguru.com/connecting-to-the-database/](https://thepythonguru.com/connecting-to-the-database/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | 在我们开始将数据库与 python 一起使用之前,必须先连接到数据库。 与 python 的数据库通信分为四个阶段: 12 | 13 | 1. 创建一个连接对象。 14 | 2. 创建一个游标对象以进行读取/写入。 15 | 3. 与数据库进行交互。 16 | 4. 关闭连接。 17 | 18 | **注意**: 19 | 20 | 我们将使用世界 mysql 数据库,因此首先[下载](http://188.166.96.119/wp-content/uploads/2015/10/world.sql_.zip)并导入数据库,如下所示: 21 | 22 | 首次登录到您的 mysql 服务器 23 | 24 | ```py 25 | mysql -u root -p 26 | 27 | ``` 28 | 29 | 此时将要求您输入密码,输入密码,然后按`Enter`键。 30 | 31 | ```py 32 | source path/to/world.sql 33 | 34 | ``` 35 | 36 | ## 连接到数据库 37 | 38 | * * * 39 | 40 | 要连接到数据库,您需要使用`connect()`方法。 41 | 42 | **语法**: 43 | 44 | ```py 45 | MySQLdb.connect( 46 | host="127.0.0.1", 47 |                 user="username", 48 |                 passwd="password", 49 |                 db="database" 50 |                ) 51 | 52 | ``` 53 | 54 | 成功后,`connect()`方法将返回一个连接对象。 否则,将引发`OperationalError`异常。 55 | 56 | ```py 57 | from __future__ import print_function 58 | 59 | import MySQLdb as my 60 | 61 | db = my.connect(host="127.0.0.1", 62 | user="root", 63 | passwd="", 64 | db="world" 65 | ) 66 | 67 | print(db) 68 | 69 | ``` 70 | 71 | 注意第一行`import print_function from __future__`中的`import`语句,这使我们能够在 Python 2 中使用 Python 3 版本的`print()`函数。 72 | 73 | **预期输出**: 74 | 75 | ```py 76 | <_mysql.connection open to '127.0.0.1' at 21fe6f0> 77 | 78 | ``` 79 | 80 | ## 创建游标对象 81 | 82 | * * * 83 | 84 | 开始与数据库进行交互之前,需要创建游标对象。 85 | 86 | **语法**:`connection_object.cursor()` 87 | 88 | 成功时,它将返回`Cursor`对象,否则将引发异常。 89 | 90 | ```py 91 | from __future__ import print_function 92 | 93 | import MySQLdb as my 94 | 95 | db = my.connect(host="127.0.0.1", 96 | user="root", 97 | passwd="", 98 | db="world" 99 | ) 100 | 101 | print(db) 102 | 103 | cursor = db.cursor() 104 | 105 | print(cursor) 106 | 107 | ``` 108 | 109 | **预期输出**: 110 | 111 | ```py 112 | <_mysql.connection open to '127.0.0.1' at 239e2c0> 113 | 114 | 115 | ``` 116 | 117 | ## 与数据库交互 118 | 119 | * * * 120 | 121 | 游标对象具有`execute()`方法,可用于执行 sql 查询。 122 | 123 | **语法**:`cursor.execute(sql)` 124 | 125 | 成功后,它将返回受影响的行数,否则将引发异常。 126 | 127 | ```py 128 | from __future__ import print_function 129 | 130 | import MySQLdb as my 131 | 132 | db = my.connect(host="127.0.0.1", 133 | user="root", 134 | passwd="", 135 | db="world" 136 | ) 137 | 138 | print(db) 139 | 140 | cursor = db.cursor() 141 | 142 | number_of_rows = cursor.execute("select * from city"); 143 | 144 | print(number_of_rows) 145 | 146 | ``` 147 | 148 | **预期输出**: 149 | 150 | ```py 151 | 4079 152 | 153 | ``` 154 | 155 | ## 断开连接 156 | 157 | * * * 158 | 159 | 与数据库进行交互之后,您需要关闭数据库连接以放弃资源。 160 | 161 | **语法**:`connection_object.close()` 162 | 163 | ```py 164 | from __future__ import print_function 165 | 166 | import MySQLdb as my 167 | 168 | db = my.connect(host="127.0.0.1", 169 | user="root", 170 | passwd="", 171 | db="world" 172 | ) 173 | 174 | print(db) 175 | 176 | cursor = db.cursor() 177 | 178 | number_of_rows = cursor.execute("select * from city"); 179 | 180 | print(number_of_rows) 181 | 182 | db.close() 183 | 184 | ``` 185 | 186 | 现在您知道了如何与数据库连接,执行查询并关闭连接。 在下一篇文章中,我们讨论如何[从表](/mysqldb-fetching-results/)中获取行。 187 | 188 | * * * 189 | 190 | * * * -------------------------------------------------------------------------------- /docs/6.md: -------------------------------------------------------------------------------- 1 | # 数据类型和变量 2 | 3 | > 原文: [https://thepythonguru.com/datatype-varibles/](https://thepythonguru.com/datatype-varibles/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | 变量是命名位置,用于存储对内存中存储的对象的引用。 我们为变量和函数选择的名称通常称为标识符。 在 Python 中,标识符必须遵守以下规则。 12 | 13 | 1. 所有标识符都必须以字母或下划线(`_`)开头,您不能使用数字。 例如:`my_var`是有效的标识符,但`1digit`不是。 14 | 2. 标识符可以包含字母,数字和下划线(`_`)。 例如:`error_404`,`_save`是有效的标识符,但`$name$`(不允许`$`)和`#age`(不允许`#`)是无效的标识符。 15 | 3. 它们可以是任何长度。 16 | 4. 标识符不能是关键字。 关键字是 Python 用于特殊目的的保留字)。 以下是 Python 3 中的关键字。 17 | 18 | ```py 19 | False class finally is return 20 | None continue for lambda try 21 | True def from nonlocal while 22 | and del global not with 23 | as elif if or yield 24 | pass else import assert 25 | break except in raise 26 | 27 | ``` 28 | 29 | ## 给变量赋值 30 | 31 | * * * 32 | 33 | 值是程序可以使用的基本东西。 例如:`1`,`11`,`3.14`和`"hello"`均为值。 在编程术语中,它们通常也称为字面值。 字面值可以是不同的类型,例如`1`,`11`是`int`类型,`3.14`是`float`和`"hello"`是`string`。 记住,在 Python 中,所有东西都是对象,甚至是基本数据类型,例如 int,float,string,我们将在后面的章节中对此进行详细说明。 34 | 35 | 在 Python 中,您不需要提前声明变量类型。 解释器通过包含的数据自动检测变量的类型。 要将值赋给变量等号(`=`)。 `=`符号也称为赋值运算符。 36 | 37 | 以下是变量声明的一些示例: 38 | 39 | ```py 40 | x = 100 # x is integer 41 | pi = 3.14 # pi is float 42 | empname = "python is great" # empname is string 43 | 44 | a = b = c = 100 # this statement assign 100 to c, b and a. 45 | 46 | ``` 47 | 48 | 试试看: 49 | 50 | ```py 51 | x = 100 # x is integer 52 | pi = 3.14 # pi is float 53 | empname = "python is great" # empname is string 54 | 55 | a = b = c = 100 # this statement assign 100 to c, b and a. 56 | 57 | print(x) # print the value of variable x 58 | print(pi) # print the value of variable pi 59 | print(empname) # print the value of variable empname 60 | print(a, b, c) # print the value of variable a, b, and c, simultaneously 61 | ``` 62 | 63 | **提示**: 64 | 65 | 将值分配给变量后,该变量本身不存储值。 而是,变量仅将对象的引用(地址)存储在内存中。 因此,在上面的清单中,变量`x`存储对`100`(`int`对象)的引用(或地址)。 变量`x`本身不存储对象`100`。 66 | 67 | ## 注释 68 | 69 | * * * 70 | 71 | 注释是说明程序目的或程序工作方式的注释。 注释不是 Python 解释器在运行程序时执行的编程语句。 注释也用于编写程序文档。 在 Python 中,任何以井号(`#`)开头的行均被视为注释。 例如: 72 | 73 | ```py 74 | # This program prints "hello world" 75 | 76 | print("hello world") 77 | 78 | ``` 79 | 80 | 试一试: 81 | 82 | ```py 83 | # This program prints "hello world" 84 | 85 | print("hello world") 86 | ``` 87 | 88 | 在此清单中,第 1 行是注释。 因此,在运行程序时,Python 解释器将忽略它。 89 | 90 | 我们还可以在语句末尾写注释。 例如: 91 | 92 | ```py 93 | # This program prints "hello world" 94 | 95 | print("hello world") # display "hello world" 96 | 97 | ``` 98 | 99 | 当注释以这种形式出现时,它们称为最终注释。 100 | 101 | 试一试: 102 | 103 | ```py 104 | # This program prints "hello world" 105 | 106 | print("hello world") # display hello world 107 | ``` 108 | 109 | ## 同时赋值 110 | 111 | * * * 112 | 113 | 同时赋值或多重赋值允许我们一次将值赋给多个变量。 同时分配的语法如下: 114 | 115 | ```py 116 | var1, var2, ..., varn = exp1, exp2, ..., expn 117 | 118 | ``` 119 | 120 | 该语句告诉 Python 求值右边的所有表达式,并将它们分配给左边的相应变量。 例如: 121 | 122 | ```py 123 | a, b = 10, 20 124 | 125 | print(a) 126 | print(b) 127 | 128 | ``` 129 | 130 | 试一试: 131 | 132 | ```py 133 | a, b = 10, 20 134 | 135 | print(a) 136 | print(b) 137 | ``` 138 | 139 | 当您想交换两个变量的值时,同时分配非常有帮助。 例如: 140 | 141 | ```py 142 | >>> x = 1 # initial value of x is 1 143 | >>> y = 2 # initial value of y is 2 144 | 145 | >>> y, x = x, y # assign y value to x and x value to y 146 | 147 | ``` 148 | 149 | **预期输出**: 150 | 151 | ```py 152 | >>> print(x) # final value of x is 2 153 | 2 154 | >>> print(y) # final value of y is 1 155 | 1 156 | 157 | ``` 158 | 159 | 试一试: 160 | 161 | ```py 162 | x = 1 # initial value of x is 1 163 | y = 2 # initial value of y is 2 164 | 165 | y, x = x, y # assign y value to x and x value to y 166 | 167 | print(x) # final value of x is 2 168 | print(y) # final value of y is 1 169 | ``` 170 | 171 | ## Python 数据类型 172 | 173 | * * * 174 | 175 | Python 即有 5 种标准数据类型。 176 | 177 | 1. 数字 178 | 2. 字符串 179 | 3. 列表 180 | 4. 元组 181 | 5. 字典 182 | 6. 布尔值 - 在 Python 中,`True`和`False`是布尔字面值。 但是以下值也被认为是`False`。 183 | * `0` - `0`,`0.0` 184 | * `[]` - 空列表,`()`-空元组,`{}`-空字典,`''` 185 | * `None` 186 | 187 | ## 从控制台接收输入 188 | 189 | * * * 190 | 191 | `input()`函数用于从控制台接收输入。 192 | 193 | **语法**: `input([prompt]) -> string` 194 | 195 | `input()`函数接受一个名为`prompt`的可选字符串参数,并返回一个字符串。 196 | 197 | ```py 198 | >>> name = input("Enter your name: ") 199 | >>> Enter your name: tim 200 | >>> name 201 | 'tim' 202 | 203 | ``` 204 | 205 | 试一试: 206 | 207 | ```py 208 | name = input("Enter your name: ") 209 | print(name) 210 | ``` 211 | 212 | 请注意,即使输入了数字,`input()`函数也始终返回字符串。 要将其转换为整数,可以使用`int()`或 [`eval()`](/python-builtin-functions/eval/)函数。 213 | 214 | ```py 215 | >>> age = int(input("Enter your age: ")) 216 | Enter your age: 22 217 | >>> age 218 | 22 219 | >>> type(age) 220 | 221 | 222 | ``` 223 | 224 | 试一试: 225 | 226 | ```py 227 | age = int(input("Enter your age: ")) 228 | 229 | print(age) 230 | print(type(age)) 231 | ``` 232 | 233 | ## 导入模块 234 | 235 | * * * 236 | 237 | Python 使用模块组织代码。 Python 随附了许多内置模块,可用于例如数学相关函数的`math`模块,正则表达式的`re`模块,与操作系统相关的函数的`os`模块等。 238 | 239 | 要使用模块,我们首先使用`import`语句将其导入。 其语法如下: 240 | 241 | ```py 242 | import module_name 243 | 244 | ``` 245 | 246 | 我们还可以使用以下语法导入多个模块: 247 | 248 | ```py 249 | import module_name_1, module_name_2 250 | 251 | ``` 252 | 253 | 这是一个例子 254 | 255 | ```py 256 | >>> import math, os 257 | >>> 258 | >>> math.pi 259 | 3.141592653589793 260 | >>> 261 | >>> math.e 262 | 2.718281828459045 263 | >>> 264 | >>> 265 | >>> os.getcwd() # print current working directory 266 | >>> '/home/user' 267 | >>> 268 | 269 | ``` 270 | 271 | 试一试: 272 | 273 | ```py 274 | import math, os 275 | 276 | print(math.pi) 277 | print(math.e) 278 | 279 | print(os.getcwd()) 280 | ``` 281 | 282 | 在此清单中,第一行导入了`math`和`os`模块中定义的所有函数,类,变量和常量。 要访问模块中定义的对象,我们首先编写模块名称,后跟点(`.`),然后编写对象本身的名称。 (即类或函数或常量或变量)。 在上面的示例中,我们从`math`数学访问两个常见的数学常数`pi`和`e`。 在下一行中,我们将调用`os`模块的`getcwd()`函数,该函数将打印当前工作目录。 283 | 284 | 在下一章中,我们将介绍 Python 中的[数字](/python-numbers/)。 285 | 286 | * * * 287 | 288 | * * * -------------------------------------------------------------------------------- /docs/60.md: -------------------------------------------------------------------------------- 1 | # MySQLdb 获取结果 2 | 3 | > 原文: [https://thepythonguru.com/fetching-results/](https://thepythonguru.com/fetching-results/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | 在上一篇文章中,我们看到了如何使用`execute()`方法执行 sql 查询。 `execute()`方法返回受影响的行,但不返回结果。 要获取结果,我们使用游标对象的`fetchall()`方法。 12 | 13 | **语法**: `cursor.fetchall()` 14 | 15 | 成功后,它将返回行的元组,其中每一行都是一个元组。 16 | 17 | ```py 18 | from __future__ import print_function 19 | 20 | import MySQLdb as my 21 | 22 | db = my.connect(host="127.0.0.1", 23 | user="root", 24 | passwd="", 25 | db="world" 26 | ) 27 | 28 | cursor = db.cursor() 29 | 30 | number_of_rows = cursor.execute("select * from city"); 31 | 32 | result = cursor.fetchall() 33 | 34 | print(result) 35 | 36 | db.close() 37 | 38 | ``` 39 | 40 | 上面的代码将打印城市表中的所有行。 41 | 42 | 您也可以使用`for`循环遍历结果。 43 | 44 | ```py 45 | from __future__ import print_function 46 | 47 | import MySQLdb as my 48 | 49 | db = my.connect(host="127.0.0.1", 50 | user="root", 51 | passwd="", 52 | db="world" 53 | ) 54 | 55 | cursor = db.cursor() 56 | 57 | number_of_rows = cursor.execute("select * from city"); 58 | 59 | result = cursor.fetchall() 60 | for row in result: 61 | print(row) 62 | 63 | db.close() 64 | 65 | ``` 66 | 67 | 一些更多的例子。 68 | 69 | **示例 1**: 70 | 71 | ```py 72 | from __future__ import print_function 73 | 74 | import MySQLdb as my 75 | 76 | db = my.connect(host="127.0.0.1", 77 | user="root", 78 | passwd="", 79 | db="world" 80 | ) 81 | 82 | cursor = db.cursor() 83 | 84 | id = 10 85 | 86 | operation = ">" 87 | 88 | sql = "select * from city where id {} {}".format(operation, id) 89 | 90 | number_of_rows = cursor.execute(sql) 91 | 92 | result = cursor.fetchall() 93 | for row in result: 94 | print(row[0], row[1]) 95 | 96 | db.close() 97 | 98 | ``` 99 | 100 | **示例 2**: 101 | 102 | ```py 103 | from __future__ import print_function 104 | 105 | import MySQLdb as my 106 | 107 | db = my.connect(host="127.0.0.1", 108 | user="root", 109 | passwd="", 110 | db="world" 111 | ) 112 | 113 | cursor = db.cursor() 114 | city = "%pur%" 115 | 116 | sql = "select * from city where name like '{}'".format(city) 117 | 118 | number_of_rows = cursor.execute(sql) 119 | 120 | result = cursor.fetchall() 121 | for row in result: 122 | print(row[0], row[1]) 123 | 124 | db.close() 125 | 126 | ``` 127 | 128 | 在下一篇文章中,我们讨论如何[将行插入数据库](/inserting-rows/)中。 129 | 130 | * * * 131 | 132 | * * * -------------------------------------------------------------------------------- /docs/61.md: -------------------------------------------------------------------------------- 1 | # 插入行 2 | 3 | > 原文: [https://thepythonguru.com/inserting-rows/](https://thepythonguru.com/inserting-rows/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | Insert 语句用于在 mysql 中插入记录。 12 | 13 | **语法**: `INSERT INTO () VALUES("");` 14 | 15 | **示例 1**: 16 | 17 | ```py 18 | from __future__ import print_function 19 | 20 | import MySQLdb as my 21 | 22 | db = my.connect(host="127.0.0.1", 23 | user="root", 24 | passwd="", 25 | db="world" 26 | ) 27 | 28 | cursor = db.cursor() 29 | 30 | sql = "insert into city VALUES(null, 'Mars City', 'MAC', 'MARC', 1233)" 31 | 32 | number_of_rows = cursor.execute(sql) 33 | db.commit() # you need to call commit() method to save 34 | # your changes to the database 35 | 36 | db.close() 37 | 38 | ``` 39 | 40 | 该程序在城市表中插入一个新城市,注意对`db.commit()`的使用,该方法将您的更改保存到数据库中。 41 | 42 | **示例 2**: 43 | 44 | ```py 45 | from __future__ import print_function 46 | 47 | import MySQLdb as my 48 | 49 | db = my.connect(host="127.0.0.1", 50 | user="root", 51 | passwd="", 52 | db="world" 53 | ) 54 | 55 | cursor = db.cursor() 56 | 57 | name = "Some new city" 58 | country_code = 'PSE' 59 | district = 'Someyork' 60 | population = 10008 61 | 62 | sql = "insert into city VALUES(null, '%s', '%s', '%s', %d)" % \ 63 | (name, country_code , district, population) 64 | 65 | number_of_rows = cursor.execute(sql) 66 | db.commit() 67 | 68 | db.close() 69 | 70 | ``` 71 | 72 | 请注意,在第 18 行中使用了反斜杠(`\`)字符。`\`字符用于将 python 语句拆分为多行。 73 | 74 | ## 插入多行 75 | 76 | * * * 77 | 78 | 要在表中插入多行,请使用游标对象的`executemany()`方法。 79 | 80 | **语法**: `cursor_object.executemany(statement, arguments)` 81 | 82 | **`statement`**:包含要执行的查询的字符串。 83 | 84 | **`arguments`**:一个包含要在`insert`语句中使用的值的序列。 85 | 86 | 让我们举个例子。 87 | 88 | ```py 89 | from __future__ import print_function 90 | 91 | import MySQLdb as my 92 | 93 | db = my.connect(host="127.0.0.1", 94 | user="root", 95 | passwd="", 96 | db="world" 97 | ) 98 | 99 | cursor = db.cursor() 100 | name = "Some new city" 101 | 102 | country_code = 'SNC' 103 | 104 | district = 'Someyork' 105 | 106 | population = 10008 107 | 108 | data = [ 109 | ('city 1', 'MAC', 'distrct 1', 16822), 110 | ('city 2', 'PSE', 'distrct 2', 15642), 111 | ('city 3', 'ZWE', 'distrct 3', 11642), 112 | ('city 4', 'USA', 'distrct 4', 14612), 113 | ('city 5', 'USA', 'distrct 5', 17672), 114 | ] 115 | 116 | sql = "insert into city(name, countrycode, district, population) 117 | VALUES(%s, %s, %s, %s)" 118 | 119 | number_of_rows = cursor.executemany(sql, data) 120 | db.commit() 121 | 122 | db.close() 123 | 124 | ``` 125 | 126 | 在下一篇文章中,我们讨论[如何处理错误](/handling-errors/)。 127 | 128 | * * * 129 | 130 | * * * -------------------------------------------------------------------------------- /docs/62.md: -------------------------------------------------------------------------------- 1 | # 处理错误 2 | 3 | > 原文: [https://thepythonguru.com/handling-errors/](https://thepythonguru.com/handling-errors/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | 与数据库交互是一个容易出错的过程,因此我们必须始终实现某种机制来优雅地处理错误。 12 | 13 | MySQLdb 具有`MySQLdb.Error`异常,这是一个顶级异常,可用于捕获`MySQLdb`模块引发的所有数据库异常。 14 | 15 | ```py 16 | from __future__ import print_function 17 | 18 | import MySQLdb as my 19 | 20 | try: 21 | 22 | db = my.connect(host="127.0.0.1", 23 | user="root", 24 | passwd="", 25 | db="world" 26 | ) 27 | 28 | cursor = db.cursor() 29 | 30 | sql = "select * from city" 31 | number_of_rows = cursor.execute(sql) 32 | print(number_of_rows) 33 | db.close() 34 | 35 | except my.Error as e: 36 | print(e) 37 | 38 | except : 39 | print("Unknown error occurred") 40 | 41 | ``` 42 | 43 | ## MySQLdb 中的两个主要错误 44 | 45 | * * * 46 | 47 | 需要注意的是,MySQLdb 中有两类异常类: 48 | 49 | 1. `DatabaseError` 50 | 2. `InterfaceError` 51 | 52 | * * * 53 | 54 | 1. **`DatabaseError`**:当数据处理中存在问题,sql 语法错误,mysql 内部问题时,引发此异常。 如果建立连接并且出现问题,则`DatabaseError`会捕获到它。 55 | 56 | 2. **`InterfaceError`**:当由于某种原因数据库连接失败时,MySQLdb 将引发`InterfaceError`。 注意`InterfaceError`仅在与数据库连接存在内部问题时才引发,MySQLdb 不会因错误的数据库名称或密码而引发`InterfaceError`。 57 | 58 | `DatabaseError`进一步分为 6 种类型: 59 | 60 | 1. `DataError` 61 | 2. `InternalError` 62 | 3. `IntegrityError` 63 | 4. `OperationalError` 64 | 5. `NotSupportedError` 65 | 6. `ProgrammingError` 66 | 67 | * * * 68 | 69 | 1. **`DataError`**:当数据处理出现问题时,例如除以零,范围的数值,MySQLdb 会引发此错误。 70 | 71 | 2. **`InternalError`**:当 MySQL 数据库本身存在一些内部错误时,引发此异常。 例如无效的游标,事务不同步等。 72 | 73 | 3. **`IntegrityError`**:当外键检查失败时,引发此异常。 74 | 75 | 4. **`OperationalError`**:对于不受程序员控制的事情,会引发此异常。 例如,意外断开连接,内存分配错误等,所选数据库不存在。 76 | 77 | 5. **`NotSupportedError`**:当存在不支持的方法或 api 时,引发此异常。 78 | 79 | 6. **`ProgrammingError`**:引发此编程错误。 例如找不到表,mysql 语法错误,指定的参数数量错误等。 80 | 81 | ```py 82 | from __future__ import print_function 83 | 84 | import MySQLdb as my 85 | 86 | try: 87 | 88 | db = my.connect(host="127.0.0.1", 89 | user="root", 90 | passwd="", 91 | db="world" 92 | ) 93 | 94 | cursor = db.cursor() 95 | 96 | sql = "select * from city" 97 | number_of_rows = cursor.execute(sql) 98 | print(number_of_rows) 99 | db.close() 100 | 101 | except my.DataError as e: 102 | print("DataError") 103 | print(e) 104 | 105 | except my.InternalError as e: 106 | print("InternalError") 107 | print(e) 108 | 109 | except my.IntegrityError as e: 110 | print("IntegrityError") 111 | print(e) 112 | 113 | except my.OperationalError as e: 114 | print("OperationalError") 115 | print(e) 116 | 117 | except my.NotSupportedError as e: 118 | print("NotSupportedError") 119 | print(e) 120 | 121 | except my.ProgrammingError as e: 122 | print("ProgrammingError") 123 | print(e) 124 | 125 | except : 126 | print("Unknown error occurred") 127 | 128 | ``` 129 | 130 | 在下一篇文章中,我们讨论[如何从数据库](/fetching-records-using-fetchone-and-fetchmany/)中获取特定的行数。 131 | 132 | * * * 133 | 134 | * * * -------------------------------------------------------------------------------- /docs/63.md: -------------------------------------------------------------------------------- 1 | # 使用`fetchone()`和`fetchmany()`获取记录 2 | 3 | > 原文: [https://thepythonguru.com/fetching-records-using-fetchone-and-fetchmany/](https://thepythonguru.com/fetching-records-using-fetchone-and-fetchmany/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | 到目前为止,我们一直在使用游标对象的`fetchall()`方法来获取记录。 一次性访问所有记录的过程并非十分有效。 结果,MySQLdb 具有游标对象的`fetchone()`和`fetchmany()`方法来更有效地获取记录。 12 | 13 | | 方法 | 描述 | 14 | | --- | --- | 15 | | `fetchone()` | 此方法以元组形式返回一个记录,如果没有更多记录,则返回`None`。 | 16 | | `fetchmany(number_of_records)` | 此方法接受要提取的记录数,并返回元组,其中每个记录本身就是一个元组。 如果没有更多记录,则返回一个空元组。 | 17 | 18 | ## 使用`fetchone()` 19 | 20 | * * * 21 | 22 | ```py 23 | from __future__ import print_function 24 | 25 | import MySQLdb as my 26 | 27 | try: 28 | 29 | db = my.connect(host="127.0.0.1", 30 | user="root", 31 | passwd="", 32 | db="world" 33 | ) 34 | 35 | cursor = db.cursor() 36 | 37 | sql = "select * from city where id < 10" 38 | number_of_rows = cursor.execute(sql) 39 | 40 | print(cursor.fetchone()) # fetch the first row only 41 | 42 | db.close() 43 | 44 | except my.DataError as e: 45 | print("DataError") 46 | print(e) 47 | 48 | except my.InternalError as e: 49 | print("InternalError") 50 | print(e) 51 | 52 | except my.IntegrityError as e: 53 | print("IntegrityError") 54 | print(e) 55 | 56 | except my.OperationalError as e: 57 | print("OperationalError") 58 | print(e) 59 | 60 | except my.NotSupportedError as e: 61 | print("NotSupportedError") 62 | print(e) 63 | 64 | except my.ProgrammingError as e: 65 | print("ProgrammingError") 66 | print(e) 67 | 68 | except : 69 | print("Unknown error occurred") 70 | 71 | ``` 72 | 73 | ## 使用`fetchone()`遍历结果 74 | 75 | * * * 76 | 77 | ```py 78 | from __future__ import print_function 79 | 80 | import MySQLdb as my 81 | 82 | try: 83 | 84 | db = my.connect(host="127.0.0.1", 85 | user="root", 86 | passwd="", 87 | db="world" 88 | ) 89 | 90 | cursor = db.cursor() 91 | 92 | sql = "select * from city where id < 10" 93 | number_of_rows = cursor.execute(sql) 94 | 95 | while True: 96 | row = cursor.fetchone() 97 | if row == None: 98 | break 99 | print(row) 100 | 101 | db.close() 102 | 103 | except my.DataError as e: 104 | print("DataError") 105 | print(e) 106 | 107 | except my.InternalError as e: 108 | print("InternalError") 109 | print(e) 110 | 111 | except my.IntegrityError as e: 112 | print("IntegrityError") 113 | print(e) 114 | 115 | except my.OperationalError as e: 116 | print("OperationalError") 117 | print(e) 118 | 119 | except my.NotSupportedError as e: 120 | print("NotSupportedError") 121 | print(e) 122 | 123 | except my.ProgrammingError as e: 124 | print("ProgrammingError") 125 | print(e) 126 | 127 | except : 128 | print("Unknown error occurred") 129 | 130 | ``` 131 | 132 | ## 使用`fetchmany()` 133 | 134 | * * * 135 | 136 | ```py 137 | from __future__ import print_function 138 | 139 | import MySQLdb as my 140 | 141 | try: 142 | 143 | db = my.connect(host="127.0.0.1", 144 | user="root", 145 | passwd="", 146 | db="world" 147 | ) 148 | 149 | cursor = db.cursor() 150 | 151 | sql = "select * from city where id < 10" 152 | number_of_rows = cursor.execute(sql) 153 | 154 | print(cursor.fetchmany(2)) # fetch first 2 rows only 155 | 156 | db.close() 157 | 158 | except my.DataError as e: 159 | print("DataError") 160 | print(e) 161 | 162 | except my.InternalError as e: 163 | print("InternalError") 164 | print(e) 165 | 166 | except my.IntegrityError as e: 167 | print("IntegrityError") 168 | print(e) 169 | 170 | except my.OperationalError as e: 171 | print("OperationalError") 172 | print(e) 173 | 174 | except my.NotSupportedError as e: 175 | print("NotSupportedError") 176 | print(e) 177 | 178 | except my.ProgrammingError as e: 179 | print("ProgrammingError") 180 | print(e) 181 | 182 | except : 183 | print("Unknown error occurred") 184 | 185 | ``` 186 | 187 | ## 使用`fetchmany()`遍历结果 188 | 189 | * * * 190 | 191 | ```py 192 | from __future__ import print_function 193 | 194 | import MySQLdb as my 195 | 196 | try: 197 | 198 | db = my.connect(host="127.0.0.1", 199 | user="root", 200 | passwd="", 201 | db="world" 202 | ) 203 | 204 | cursor = db.cursor() 205 | 206 | sql = "select * from city where id < 10" 207 | number_of_rows = cursor.execute(sql) 208 | 209 | while True: 210 | two_rows = cursor.fetchmany(2) 211 | if not two_rows: 212 | break 213 | print(two_rows) 214 | 215 | db.close() 216 | 217 | except my.DataError as e: 218 | print("DataError") 219 | print(e) 220 | 221 | except my.InternalError as e: 222 | print("InternalError") 223 | print(e) 224 | 225 | except my.IntegrityError as e: 226 | print("IntegrityError") 227 | print(e) 228 | 229 | except my.OperationalError as e: 230 | print("OperationalError") 231 | print(e) 232 | 233 | except my.NotSupportedError as e: 234 | print("NotSupportedError") 235 | print(e) 236 | 237 | except my.ProgrammingError as e: 238 | print("ProgrammingError") 239 | print(e) 240 | 241 | except : 242 | print("Unknown error occurred") 243 | 244 | ``` 245 | 246 | * * * 247 | 248 | * * * -------------------------------------------------------------------------------- /docs/64.md: -------------------------------------------------------------------------------- 1 | # 常见做法 -------------------------------------------------------------------------------- /docs/68.md: -------------------------------------------------------------------------------- 1 | # 用 Python 转储对象 2 | 3 | > 原文: [https://thepythonguru.com/pickling-objects-in-python/](https://thepythonguru.com/pickling-objects-in-python/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | 在[用 Python 阅读和编写 JSON](/reading-and-writing-json-in-python/) 一文中,我们了解了如何在 Python 中处理 JSON 数据。 如果您还没有看完这篇文章,我建议您这样做,然后再回到这里。 12 | 13 | 事实证明,`json`模块不是序列化数据的唯一方法。 Python 提供了另一个名为`pickle`的模块来对数据进行序列化和反序列化。 14 | 15 | 这是`json`和`pickle`模块之间的主要区别。 16 | 17 | 1. `pickle`模块是特定于 Python 的,这意味着对象被序列化后,就不能使用其他语言(如 PHP,Java,Perl 等)反序列化。如果需要互操作性,则请坚持使用`json`模块。 18 | 19 | 2. 与`json`模块将对象序列化为人类可读的 JSON 字符串不同,`pickle`模块以二进制格式序列化数据。 20 | 21 | 3. `json`模块允许我们仅序列化基本的 Python 类型(例如`int`,`str`,`dict`,`list`等)。 如果需要序列化自定义对象,则必须提供自己的序列化函数。 但是,`pickle`模块可立即使用多种 Python 类型,包括您定义的自定义对象。 22 | 23 | 4. `pickle`模块的大多数代码都是用 C 编码的。因此,与`json`模块相比,它在处理大型数据集时性能得到了极大的提高。 24 | 25 | `pickle`模块提供的接口与`json`模块相同,并且由`dump()` / `load()`和`dumps()` / `loads()`函数组成。 26 | 27 | 要使用`pickle`模块,请按以下步骤导入它: 28 | 29 | ```py 30 | >>> 31 | >>> import pickle 32 | >>> 33 | 34 | ``` 35 | 36 | 现在让我们看看如何使用`pickle`模块来序列化和反序列化对象。 37 | 38 | **注意**: 39 | 40 | *序列化*和*反序列化*有时也分别称为*转储*和*加载*。 41 | 42 | ## 用`dump()`转储 43 | 44 | * * * 45 | 46 | 转储数据通过`dump()`函数完成。 它接受数据和文件对象。 然后,`dump()`函数将数据序列化并将其写入文件。 `dump()`的语法如下: 47 | 48 | **语法**:`dump(obj, file)` 49 | 50 | | 参数 | 描述 | 51 | | --- | --- | 52 | | `obj` | 要转储的对象。 | 53 | | `file` | 将写入转储数据的文件对象。 | 54 | 55 | 这是一个例子: 56 | 57 | ```py 58 | >>> 59 | >>> import pickle 60 | >>> 61 | >>> from datetime import datetime 62 | >>> 63 | >>> 64 | >>> f = open("my_pickle", "wb") # remember to open the file in binary mode 65 | >>> 66 | >>> pickle.dump(10, f) 67 | >>> pickle.dump("a string", f) 68 | >>> pickle.dump({'a': 1, 'b': 2}, f) 69 | >>> pickle.dump(datetime.now(), f) # serialize datetime.datetime object 70 | >>> 71 | >>> f.close() 72 | >>> 73 | >>> 74 | 75 | ``` 76 | 77 | 这里有两件事要注意: 78 | 79 | 1. 首先,我们以二进制模式而不是文本模式打开文件。 这是必要的,否则在写入时数据将被破坏。 80 | 2. 其次,`dump()`函数能够对`datetime.datetime`对象进行序列化,而无需提供任何自定义序列化函数。 81 | 82 | 显然,我们不仅限于`datetime.datetime`对象。 举一个例子,以下清单对 Python 中可用的其他一些类型进行了序列化。 83 | 84 | ```py 85 | >>> 86 | >>> class My_class: 87 | ... def __init__(self, name): 88 | ... self.name = name 89 | ... 90 | >>> 91 | >>> 92 | >>> def func(): return "func() called" 93 | ... 94 | >>> 95 | >>> 96 | >>> f = open("other_pickles", "wb") 97 | >>> 98 | >>> pickle.dump(My_class, f) # serialize class object 99 | >>> 100 | >>> pickle.dump(2 + 3j, f) # serialize complex number 101 | >>> 102 | >>> pickle.dump(func, f) # serialize function object 103 | >>> 104 | >>> pickle.dump(bytes([1, 2, 3, 4, 5]), f) # serialize bytes object 105 | >>> 106 | >>> pickle.dump(My_class("name"), f) # serialize class instance 107 | >>> 108 | >>> f.close() 109 | >>> 110 | >>> 111 | 112 | ``` 113 | 114 | 我们现在转储了一些数据。 此时,如果您尝试从文件中读取数据,则会将数据作为`bytes`对象获得。 115 | 116 | ```py 117 | >>> 118 | >>> open("my_pickle", "rb").read() 119 | b'\x80\x03K\n.\x80\x03X\x08\x00\x00\x00a stringq\x00.\x80\x03}q\x00(X\x01\x00\x00\x00bq\x01K\x02X\x01\x00\x00\x00aq\x02K\x01u.\x80\x03cdatetime\ndatetime\nq\x00C\n\x07\xe2\t\x1e\x10.\x1e\r9\x92q\x01\x85q\x02Rq\x03.' 120 | >>> 121 | >>> 122 | >>> open("other_pickles", "rb").read() 123 | b'\x80\x03c__main__\nMy_Class\nq\x00.\x80\x03cbuiltins\ncomplex\nq\x00G@\x00\x00\x00\x00\x00\x00\x00G@\x08\x00\x00\x00\x00\x00\x00\x86q\x01Rq\x02.\x80\x03c__main__\nfunc\nq\x00.\x80\x03C\x05\x01\x02\x03\x04\x05q\x00.\x80\x03c__main__\nMy_Class\nq\x00)\x81q\x01}q\x02X\x04\x00\x00\x00nameq\x03h\x03sb.' 124 | >>> 125 | >>> 126 | 127 | ``` 128 | 129 | 这不是很可读。 对? 130 | 131 | 要恢复拾取的对象,我们使用`load()`函数 132 | 133 | ## 用`load()`加载 134 | 135 | * * * 136 | 137 | `load()`函数获取一个文件对象,从转储的表示中重建对象,然后将其返回。 138 | 139 | 其语法如下: 140 | 141 | | 参数 | 描述 | 142 | | --- | --- | 143 | | `file` | 从中读取序列化数据的文件对象。 | 144 | 145 | 现在,让我们尝试阅读我们在本文前面创建的`my_pickle`文件。 146 | 147 | ```py 148 | >>> 149 | >>> f = open("my_pickle", "rb") 150 | >>> 151 | >>> pickle.load(f) 152 | 10 153 | >>> pickle.load(f) 154 | 'a string' 155 | >>> 156 | >>> pickle.load(f) 157 | {'b': 2, 'a': 1} 158 | >>> 159 | >>> pickle.load(f) 160 | datetime.datetime(2018, 9, 30, 16, 46, 30, 866706) 161 | >>> 162 | >>> pickle.load(f) 163 | Traceback (most recent call last): 164 | File "", line 1, in 165 | EOFError: Ran out of input 166 | >>> 167 | >>> f.close() 168 | >>> 169 | 170 | ``` 171 | 172 | 注意,对象的返回顺序与我们首先对其进行转储的顺序相同。 另外,请注意,该文件以二进制模式打开以进行读取。 当没有更多数据要返回时,`load()`函数将引发`EOFError`。 173 | 174 | 同样,我们可以从`other_pickles`文件中读取转储的数据。 175 | 176 | ```py 177 | >>> 178 | >>> 179 | >>> f = open("other_pickles", "rb") # open the file for reading in binary mode 180 | >>> 181 | >>> My_class = pickle.load(f) 182 | 183 | >>> 184 | >>> 185 | >>> c = pickle.load(f) 186 | >>> 187 | >>> c 188 | (2+3j) 189 | >>> 190 | >>> 191 | >>> func = pickle.load(f) 192 | >>> 193 | >>> func 194 | 195 | >>> 196 | >>> 197 | >>> b = pickle.load(f) 198 | >>> 199 | >>> b 200 | b'\x01\x02\x03\x04\x05' 201 | >>> 202 | >>> 203 | >>> my_class_obj = pickle.load(f) 204 | >>> my_class_obj 205 | <__main__.My_Class object at 0x7f9aa74e61d0> 206 | >>> 207 | >>> 208 | >>> pickle.load(f) 209 | Traceback (most recent call last): 210 | File "", line 1, in 211 | EOFError: Ran out of input 212 | >>> 213 | >>> 214 | >>> f.close() 215 | >>> 216 | >>> 217 | 218 | ``` 219 | 220 | 加载数据后,就可以像普通的 Python 对象一样使用它了。 221 | 222 | ```py 223 | >>> 224 | >>> func() 225 | 'func() called' 226 | >>> 227 | >>> 228 | >>> c.imag, c.real 229 | (3.0, 2.0) 230 | >>> 231 | >>> 232 | >>> My_class("Tom") 233 | <__main__.My_Class object at 0x7f9aa74e6358> 234 | >>> 235 | >>> 236 | >>> my_class_obj.name 237 | 'name' 238 | >>> 239 | >>> 240 | 241 | ``` 242 | 243 | ## 使用`dumps()`和`load()`进行转储和加载 244 | 245 | * * * 246 | 247 | `dumps()`的工作方式与`dump()`完全相同,但是它不是将输出发送到文件,而是将转储的数据作为字符串返回。 其语法如下: 248 | 249 | **语法**:`dumps(obj) -> pickled_data` 250 | 251 | | 参数 | 描述 | 252 | | --- | --- | 253 | | `obj` | 要序列化的对象 | 254 | 255 | 同样,`loads()`函数与`load()`相同,但是它不是从文件中读取转储的数据,而是从字符串中读取数据。 其语法如下: 256 | 257 | **语法**:`loads(pickled_data) -> obj` 258 | 259 | | 参数 | 描述 | 260 | | --- | --- | 261 | | `pickled_data` | 转储数据 | 262 | 263 | Here is an example: 264 | 265 | ```py 266 | >>> 267 | >>> employee = { 268 | ... "first_name": "Mike", 269 | ... "designation": 'Manager', 270 | ... "doj": datetime(year=2016, month=5, day=2), # date of joining 271 | ... } 272 | >>> 273 | >>> 274 | >>> pickled_emp = pickle.dumps(employee) # pickle employee dictionary 275 | >>> 276 | >>> pickled_emp 277 | b'\x80\x03}q\x00(X\x0b\x00\x00\x00designationq\x01X\x07\x00\x00\x00Managerq\x02X\x03\x00\x00\x00dojq\x03cdatetime\ndatetime\nq\x04C\n\x07\xe0\x05\x02\x00\x00\x00\x00\x00\x00q\x05\x85q\x06Rq\x07X\n\x00\x00\x00first_nameq\x08X\x04\x00\x00\x00Mikeq\tu.' 278 | >>> 279 | >>> 280 | >>> pickle.loads(pickled_emp) # unpickle employee dictionary 281 | {'designation': 'Manager', 'doj': datetime.datetime(2016, 5, 2, 0, 0), 'first_name': 'Mike'} 282 | >>> 283 | >>> 284 | 285 | ``` 286 | 287 | 请记住,当您释放数据时,对象会浮现,因此切勿尝试处理来自不受信任来源的转储数据。 恶意用户可以使用这种技术在系统上执行任意命令。 288 | 289 | * * * 290 | 291 | * * * -------------------------------------------------------------------------------- /docs/7.md: -------------------------------------------------------------------------------- 1 | # Python 数字 2 | 3 | > 原文: [https://thepythonguru.com/python-numbers/](https://thepythonguru.com/python-numbers/) 4 | 5 | * * * 6 | 7 | 于 2020 年 5 月 7 日更新 8 | 9 | * * * 10 | 11 | 此数据类型仅支持诸如`1`,`31.4`,`-1000`,`0.000023`和`88888888`之类的数值。 12 | 13 | Python 支持 3 种不同的数字类型。 14 | 15 | 1. `int`-用于整数值,例如`1`,`100`,`2255`,`-999999`,`0`和`12345678`。 16 | 2. `float`-用于像`2.3`,`3.14`,`2.71`,`-11.0`之类的浮点值。 17 | 3. `complex`-适用于`3+2j`,`-2+2.3j`,`10j`,`4.5+3.14j`等复数。 18 | 19 | ## 整数 20 | 21 | * * * 22 | 23 | python 中的整数字面值属于`int`类。 24 | 25 | ```py 26 | >>> i = 100 27 | >>> i 28 | 100 29 | 30 | ``` 31 | 32 | ## 浮点数 33 | 34 | * * * 35 | 36 | 浮点数是带有小数点的值。 37 | 38 | ```py 39 | >>> f = 12.3 40 | >>> f 41 | 12.3 42 | 43 | ``` 44 | 45 | 需要注意的一点是,当数字运算符的操作数之一是浮点值时,结果将是浮点值。 46 | 47 | ```py 48 | >>> 3 * 1.5 49 | 4.5 50 | 51 | ``` 52 | 53 | ## 复数 54 | 55 | * * * 56 | 57 | 如您所知,复数由实部和虚部两部分组成,用`j`表示。 您可以这样定义复数: 58 | 59 | ```py 60 | >>> x = 2 + 3j # where 2 is the real part and 3 is imaginary 61 | 62 | ``` 63 | 64 | ## 确定类型 65 | 66 | * * * 67 | 68 | Python 具有`type()`内置函数,可用于确定变量的类型。 69 | 70 | ```py 71 | >>> x = 12 72 | >>> type(x) 73 |   74 | 75 | ``` 76 | 77 | ## Python 运算符 78 | 79 | * * * 80 | 81 | Python 具有不同的运算符,可让您在程序中执行所需的计算。 82 | 83 | `+`,`-`和`*`可以正常工作,其余的运算符需要一些解释。 84 | 85 | | 名称 | 含义 | 示例 | 结果 | 86 | | --- | --- | --- | --- | 87 | | `+` | 加法 | `15+20` | `35` | 88 | | `-` | 减法 | `24.5-3.5` | `21.0` | 89 | | `*` | 乘法 | `15*4` | `60` | 90 | | `/` | 浮点除法 | `4/5` | `0.8` | 91 | | `//` | 整数除法 | `4//5` | `0` | 92 | | `**` | 求幂 | `4**2` | `16` | 93 | | `%` | 余数 | `27%4` | `3` | 94 | 95 | **浮点除法(`/`)**:`/`运算符进行除法并以浮点数形式返回结果,这意味着它将始终返回小数部分。 例如 96 | 97 | ```py 98 | >>> 3/2  99 | 1.5 100 | 101 | ``` 102 | 103 | **整数除法(`//`)**:`//`执行整数除法,即它将截断答案的小数部分并仅返回整数。 104 | 105 | ```py 106 | >>> 3//2  107 | 1 108 | 109 | ``` 110 | 111 | **幂运算符(`**`)**:此运算符有助于计算`^b`(a 的 b 次幂)。 让我们举个例子: 112 | 113 | ```py 114 | >>> 2 ** 3 # is same as 2 * 2 * 2 115 | 8 116 | ``` 117 | 118 | **余数运算符(`%`)**:`%`运算符也称为余数或模数运算符。 该运算符除法后返回余数。 例如: 119 | 120 | ```py 121 | >>> 7 % 2 122 | 1 123 | 124 | ``` 125 | 126 | ## 运算符优先级 127 | 128 | * * * 129 | 130 | 在 python 中,每个表达式都使用运算符优先级进行求值。 让我们以一个例子来阐明它。 131 | 132 | ```py 133 | >>> 3 * 4 + 1 134 | 135 | ``` 136 | 137 | 在上面的表达式中,将对哪个运算进行第一个加法或乘法运算? 为了回答这样的问题,我们需要在 python 中引用运算符优先级列表。 下图列出了 python 优先级从高到低的顺序。 138 | 139 | ![python-operator-precedence1.jpg](img/1bd07b9ee86ea977adf3c113fe0e0939.png) 140 | 141 | 如您在上表中所见`*`在`+`之上,因此`*`将首先出现,然后加法。 因此,以上表达式的结果将为`13`。 142 | 143 | ```py 144 | >>> 3 * 4 + 1 145 | >>> 13 146 | 147 | ``` 148 | 149 | 让我们再举一个例子来说明另一个概念。 150 | 151 | ```py 152 | >>> 3 + 4 - 2 153 | 154 | ``` 155 | 156 | 在以上表达式中,将首先进行加法或减法。 从表`+`和`-`的优先级相同,然后将它们从左到右进行求值,即先加法,然后减法。 157 | 158 | ```py 159 | >>> 3 + 4 - 2 160 | >>> 5 161 | 162 | ``` 163 | 164 | 该规则的唯一例外是赋值运算符(`=`),它从右到左出现。 165 | 166 | ```py 167 | a = b = c 168 | 169 | ``` 170 | 171 | 您可以使用括号`()`更改优先级,例如: 172 | 173 | ```py 174 | >> 3 * (4 + 1) 175 | >> 15 176 | 177 | ``` 178 | 179 | 从优先级表中可以看出,`()`具有最高优先级,因此在表达式`3 * (4 + 1)`中,先求值`(4 + 1)`,然后相乘。 因此,您可以使用`()`更改优先级。 180 | 181 | ## 复合赋值 182 | 183 | * * * 184 | 185 | 这些运算符使您可以编写快捷方式分配语句。 例如: 186 | 187 | ```py 188 | >>> count = 1 189 | >>> count = count + 1 190 | >>> count 191 | 2 192 | 193 | ``` 194 | 195 | 通过使用增强分配运算符,我们可以将其编写为: 196 | 197 | ```py 198 | >>> count = 1 199 | >>> count += 1 200 | >>> count 201 | 2 202 | 203 | ``` 204 | 205 | 类似地,您可以将`-`,`%`,`//`,`/`,`*`和`**`与赋值运算符一起使用以构成扩展赋值运算符。 206 | 207 | | 运算符 | 名称 | 示例 | 等价于 | 208 | | --- | --- | --- | --- | 209 | | `+=` | 加法赋值 | `x += 4` | `x = x + 4` | 210 | | `-=` | 减法赋值 | `x -= 2` | `x = x - 2` | 211 | | `*=` | 乘法赋值 | `x *= 5` | `x = x * 5` | 212 | | `/*=` | 除法赋值 | `x /= 5` | `x = x / 5` | 213 | | `//*=` | 整数除法赋值 | `x //= 5` | `x = x // 5` | 214 | | `%*=` | 余数赋值 | `x %= 5` | `x = x % 5` | 215 | | `**=` | 指数赋值 | `x **= 5` | `x = x ** 5` | 216 | 217 | 在下一篇文章中,我们将学习 python 字符串。 218 | 219 | * * * 220 | 221 | * * * -------------------------------------------------------------------------------- /docs/9.md: -------------------------------------------------------------------------------- 1 | # Python 列表 2 | 3 | > 原文: [https://thepythonguru.com/python-lists/](https://thepythonguru.com/python-lists/) 4 | 5 | * * * 6 | 7 | 于 2020 年 1 月 7 日更新 8 | 9 | * * * 10 | 11 | 列表类型是 python 的列表类定义的另一种序列类型。 列表允许您以非常简单的方式添加,删除或处理元素。 列表与数组非常相似。 12 | 13 | ## 在 python 中创建列表 14 | 15 | * * * 16 | 17 | 您可以使用以下语法创建列表。 18 | 19 | ```py 20 | >>> l = [1, 2, 3, 4] 21 | 22 | ``` 23 | 24 | 在此,列表中的每个元素都用逗号分隔,并用一对方括号(`[]`)包围。 列表中的元素可以是相同类型或不同类型。 例如: 25 | 26 | ```py 27 | l2 = ["this is a string", 12] 28 | 29 | ``` 30 | 31 | 创建列表的其他方式。 32 | 33 | ```py 34 | list1 = list() # Create an empty list 35 | list2 = list([22, 31, 61]) # Create a list with elements 22, 31, 61 36 | list3 = list(["tom", "jerry", "spyke"]) # Create a list with strings 37 | list5 = list("python") # Create a list with characters p, y, t, h, o, n 38 | 39 | ``` 40 | 41 | **注意**: 42 | 43 | 列表是可变的。 44 | 45 | ## 访问列表中的元素 46 | 47 | * * * 48 | 49 | 您可以使用索引运算符(`[]`)访问列表中的各个元素。 列表索引从`0`开始。 50 | 51 | ```py 52 | >>> l = [1,2,3,4,5] 53 | >>> l[1] # access second element in the list 54 | 2 55 | >>> l[0] # access first element in the list 56 | 1 57 | 58 | ``` 59 | 60 | ## 常用列表操作 61 | 62 | * * * 63 | 64 | | 方法名称 | 描述 | 65 | | --- | --- | 66 | | `x in s` | 如果元素`x`在序列`s`中,则为`True`,否则为`False` | 67 | | `x not in s` | 如果元素`x`不在序列`s`中,则为`True`,否则为`False` | 68 | | `s1 + s2` | 连接两个序列`s1`和`s2` | 69 | | `s * n`,`n * s` | 连接序列`s`的`n`个副本 | 70 | | `s[i]` | 序列`s`的第`i`个元素。 | 71 | | `len(s)` | 序列`s`的长度,也就是元素数量。 | 72 | | `min(s)` | 序列`s`中最小的元素。 | 73 | | `max(s)` | 序列`s`中最大的元素。 | 74 | | `sum(s)` | 序列`s`中所有数字的总和。 | 75 | | `for`循环 | 在`for`循环中从左到右遍历元素。 | 76 | 77 | ## 列表函数示例 78 | 79 | * * * 80 | 81 | ```py 82 | >>> list1 = [2, 3, 4, 1, 32] 83 | >>> 2 in list1 84 | True 85 | >>> 33 not in list1 86 | True 87 | >>> len(list1) # find the number of elements in the list 88 | 5 89 | >>> max(list1) # find the largest element in the list 90 | 32 91 | >>> min(list1) # find the smallest element in the list 92 | 1 93 | >>> sum(list1) # sum of elements in the list 94 | 42 95 | 96 | ``` 97 | 98 | ## 列表切片 99 | 100 | * * * 101 | 102 | 切片运算符(`[start:end]`)允许从列表中获取子列表。 它的工作原理类似于字符串。 103 | 104 | ```py 105 | >>> list = [11,33,44,66,788,1] 106 | >>> list[0:5] # this will return list starting from index 0 to index 4 107 | [11,33,44,66,788] 108 | 109 | ``` 110 | 111 | ```py 112 | >>> list[:3] 113 | [11,33,44] 114 | 115 | ``` 116 | 117 | 类似于字符串`start`的索引是可选的,如果省略,它将为`0`。 118 | 119 | ```py 120 | >>> list[2:] 121 | [44,66,788,1] 122 | 123 | ``` 124 | 125 | `end`索引也是可选的,如果省略,它将被设置为列表的最后一个索引。 126 | 127 | **注意**: 128 | 129 | 如果为`start >= end`,则`list[start : end]`将返回一个空列表。 如果`end`指定的位置超出列表的`end`,则 Python 将使用`end`的列表长度。 130 | 131 | ## 列表中的`+`和`*`运算符 132 | 133 | * * * 134 | 135 | `+`运算符加入两个列表。 136 | 137 | ```py 138 | >>> list1 = [11, 33] 139 | >>> list2 = [1, 9] 140 | >>> list3 = list1 + list2 141 | >>> list3 142 | [11, 33, 1, 9] 143 | 144 | ``` 145 | 146 | `*`操作符复制列表中的元素。 147 | 148 | ```py 149 | >>> list4 = [1, 2, 3, 4] 150 | >>> list5 = list4 * 3 151 | >>> list5 152 | [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4] 153 | 154 | ``` 155 | 156 | ## `in`或`not in`运算符 157 | 158 | * * * 159 | 160 | `in`运算符用于确定列表中是否存在元素。 成功则返回`True`;失败则返回`False`。 161 | 162 | ```py 163 | >>> list1 = [11, 22, 44, 16, 77, 98] 164 | >>> 22 in list1 165 | True 166 | 167 | ``` 168 | 169 | 同样,`not in`与`in`运算符相反。 170 | 171 | ```py 172 | >>> 22 not in list1 173 | False 174 | 175 | ``` 176 | 177 | ## 使用`for`循环遍历列表 178 | 179 | * * * 180 | 181 | 如前所述,列表是一个序列并且也是可迭代的。 意味着您可以使用`for`循环遍历列表的所有元素。 182 | 183 | ```py 184 | >>> list = [1,2,3,4,5] 185 | >>> for i in list: 186 | ... print(i, end=" ") 187 | 1 2 3 4 5 188 | 189 | ``` 190 | 191 | ## 常用列表方法和返回类型 192 | 193 | * * * 194 | 195 | | 方法 | 描述 | 196 | | --- | --- | 197 | | `append(x: object): None` | 在列表的末尾添加元素`x`并返回`None`。 | 198 | | `count(x: object): int` | 返回元素`x`在列表中出现的次数。 | 199 | | `append(l: list): None` | 将`l`中的所有元素附加到列表中并返回`None`。 | 200 | | `index(x: object): int` | 返回列表中第一次出现的元素`x`的索引 | 201 | | `insert(index: int, x: object): None` | 在给定索引处插入元素`x`。 请注意,列表中的第一个元素具有索引`0`并返回`None`。 | 202 | | `remove(x: object): None` | 从列表中删除第一次出现的元素`x`并返回`None` | 203 | | `reverse(): None` | 反转列表并返回`None` | 204 | | `sort(): None` | 按升序对列表中的元素进行排序并返回`None`。 | 205 | | `pop(i): object` | 删除给定位置的元素并返回它。 参数`i`是可选的。 如果未指定,则`pop()`删除并返回列表中的最后一个元素。 | 206 | 207 | ```py 208 | >>> list1 = [2, 3, 4, 1, 32, 4] 209 | >>> list1.append(19) 210 | >>> list1 211 | [2, 3, 4, 1, 32, 4, 19] 212 | >>> list1.count(4) # Return the count for number 4 213 | 2 214 | >>> list2 = [99, 54] 215 | >>> list1.extend(list2) 216 | >>> list1 217 | [2, 3, 4, 1, 32, 4, 19, 99, 54] 218 | >>> list1.index(4) # Return the index of number 4 219 | 2 220 | >>> list1.insert(1, 25) # Insert 25 at position index 1 221 | >>> list1 222 | [2, 25, 3, 4, 1, 32, 4, 19, 99, 54] 223 | >>> 224 | >>> list1 = [2, 25, 3, 4, 1, 32, 4, 19, 99, 54] 225 | >>> list1.pop(2) 226 | 3 227 | >>> list1 228 | [2, 25, 4, 1, 32, 4, 19, 99, 54] 229 | >>> list1.pop() 230 | 54 231 | >>> list1 232 | [2, 25, 4, 1, 32, 4, 19, 99] 233 | >>> list1.remove(32) # Remove number 32 234 | >>> list1 235 | [2, 25, 4, 1, 4, 19, 99] 236 | >>> list1.reverse() # Reverse the list 237 | >>> list1 238 | [99, 19, 4, 1, 4, 25, 2] 239 | >>> list1.sort() # Sort the list 240 | >>> list1 241 | [1, 2, 4, 4, 19, 25, 99] 242 | >>> 243 | 244 | ``` 245 | 246 | ## 列表推导式 247 | 248 | * * * 249 | 250 | **注意**: 251 | 252 | 本主题需要具有 [Python 循环](/loops/)的使用知识。 253 | 254 | 列表理解为创建列表提供了一种简洁的方法。 它由包含表达式的方括号组成,后跟`for`子句,然后是零个或多个`for`或`if`子句。 255 | 256 | 这里有些例子: 257 | 258 | ```py 259 | >>> list1 = [ x for x in range(10) ] 260 | >>> list1 261 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 262 | >>> 263 | >>> 264 | >>> list2 = [ x + 1 for x in range(10) ] 265 | >>> list2 266 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 267 | >>> 268 | >>> 269 | >>> list3 = [ x for x in range(10) if x % 2 == 0 ] 270 | >>> list3 271 | [0, 2, 4, 6, 8] 272 | >>> 273 | >>> 274 | >>> list4 = [ x *2 for x in range(10) if x % 2 == 0 ] 275 | [0, 4, 8, 12, 16] 276 | 277 | ``` 278 | 279 | 在下一个教程中,我们将学习 python 字典。 280 | 281 | * * * 282 | 283 | * * * -------------------------------------------------------------------------------- /docs/img/08b661eaec8ff40dbd5e2fbc5e7bb843.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/pythonguru-zh/50a9e308f6b667220a64ca5f98b666cf345c1586/docs/img/08b661eaec8ff40dbd5e2fbc5e7bb843.png -------------------------------------------------------------------------------- /docs/img/1465df1cc7b49f4ef431f26f7e1627ab.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/pythonguru-zh/50a9e308f6b667220a64ca5f98b666cf345c1586/docs/img/1465df1cc7b49f4ef431f26f7e1627ab.png -------------------------------------------------------------------------------- /docs/img/1bd07b9ee86ea977adf3c113fe0e0939.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/pythonguru-zh/50a9e308f6b667220a64ca5f98b666cf345c1586/docs/img/1bd07b9ee86ea977adf3c113fe0e0939.png -------------------------------------------------------------------------------- /docs/img/6113451b01106e8adff5df5b50e8d069.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/pythonguru-zh/50a9e308f6b667220a64ca5f98b666cf345c1586/docs/img/6113451b01106e8adff5df5b50e8d069.png -------------------------------------------------------------------------------- /docs/img/72eeb7f2bbb92ad38bfff7f133d3c3cc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/pythonguru-zh/50a9e308f6b667220a64ca5f98b666cf345c1586/docs/img/72eeb7f2bbb92ad38bfff7f133d3c3cc.png -------------------------------------------------------------------------------- /docs/img/96a007840d513479e414cd40e5b67e2c.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/pythonguru-zh/50a9e308f6b667220a64ca5f98b666cf345c1586/docs/img/96a007840d513479e414cd40e5b67e2c.png -------------------------------------------------------------------------------- /docs/img/a221810ac323791d4ac671449aa078e1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/pythonguru-zh/50a9e308f6b667220a64ca5f98b666cf345c1586/docs/img/a221810ac323791d4ac671449aa078e1.png -------------------------------------------------------------------------------- /docs/img/fe7cf26a723283da03ef589149ee7c3c.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/pythonguru-zh/50a9e308f6b667220a64ca5f98b666cf345c1586/docs/img/fe7cf26a723283da03ef589149ee7c3c.png -------------------------------------------------------------------------------- /docs/img/ff8e1e812772d3d072395aa647df7499.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/pythonguru-zh/50a9e308f6b667220a64ca5f98b666cf345c1586/docs/img/ff8e1e812772d3d072395aa647df7499.png -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
now loading...
31 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /update.sh: -------------------------------------------------------------------------------- 1 | git add -A 2 | git commit -am "$(date "+%Y-%m-%d %H:%M:%S")" 3 | git push --------------------------------------------------------------------------------