├── .gitignore ├── README.md ├── SUMMARY.md ├── book.json ├── data ├── 100003.md ├── 101754.md ├── 1024847.md ├── 11241523.md ├── 11277432.md ├── 1132941.md ├── 1185524.md ├── 12179271.md ├── 1231688.md ├── 123198.md ├── 1301346.md ├── 136097.md ├── 1436703.md ├── 1450393.md ├── 1602934.md ├── 1712227.md ├── 1720421.md ├── 17271319.md ├── 1747817.md ├── 176918.md ├── 1952464.md ├── 2052390.md ├── 2225038.md ├── 2257441.md ├── 231767.md ├── 252703.md ├── 2600191.md ├── 2612802.md ├── 2720014.md ├── 273192.md ├── 275018.md ├── 279237.md ├── 2817869.md ├── 2835559.md ├── 2846653.md ├── 287871.md ├── 30081275.md ├── 3061.md ├── 306400.md ├── 312443.md ├── 3207219.md ├── 3220404.md ├── 3277503.md ├── 3294889.md ├── 332289.md ├── 339007.md ├── 3394835.md ├── 3437059.md ├── 354038.md ├── 36901.md ├── 36932.md ├── 372885.md ├── 379906.md ├── 38987.md ├── 394809.md ├── 3964681.md ├── 402504.md ├── 415511.md ├── 419163.md ├── 423379.md ├── 448271.md ├── 455612.md ├── 466345.md ├── 4706499.md ├── 4750806.md ├── 4906977.md ├── 493386.md ├── 493819.md ├── 5082452.md ├── 509211.md ├── 510348.md ├── 510972.md ├── 5137497.md ├── 522563.md ├── 53513.md ├── 5466451.md ├── 5574702.md ├── 576169.md ├── 582336.md ├── 60208.md ├── 606191.md ├── 610883.md ├── 613183.md ├── 627435.md ├── 6470428.md ├── 663171.md ├── 6797984.md ├── 68645.md ├── 6996603.md ├── 72899.md ├── 735975.md ├── 739654.md ├── 82831.md ├── 89228.md ├── 930397.md ├── 931092.md ├── 9371238.md ├── 952914.md ├── 9573244.md ├── 961632.md ├── 986006.md ├── 990754.md └── 9942594.md ├── get_so_100.py ├── images └── 2846653-1.png ├── part ├── 1.md ├── 10.md ├── 100.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 ├── 69.md ├── 7.md ├── 70.md ├── 71.md ├── 72.md ├── 73.md ├── 74.md ├── 75.md ├── 76.md ├── 77.md ├── 78.md ├── 79.md ├── 8.md ├── 80.md ├── 81.md ├── 82.md ├── 83.md ├── 84.md ├── 85.md ├── 86.md ├── 87.md ├── 88.md ├── 89.md ├── 9.md ├── 90.md ├── 91.md ├── 92.md ├── 93.md ├── 94.md ├── 95.md ├── 96.md ├── 97.md ├── 98.md └── 99.md └── test.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Node rules: 2 | ## Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 3 | .grunt 4 | 5 | ## Dependency directory 6 | ## Commenting this out is preferred by some people, see 7 | ## https://docs.npmjs.com/misc/faq#should-i-check-my-node_modules-folder-into-git 8 | node_modules 9 | 10 | # Book build output 11 | _book 12 | 13 | # eBook build output 14 | *.epub 15 | *.mobi 16 | *.pdf 17 | -------------------------------------------------------------------------------- /SUMMARY.md: -------------------------------------------------------------------------------- 1 | 2 | # Summary 3 | 4 | ## 简介 5 | 6 | * [Introduction](README.md) 7 | 8 | ## TOP 100 9 | 10 | * [Python中关键字yield有什么作用?](part/1.md) 11 | * [`if __name__ == "__main__":`有什么作用?](part/2.md) 12 | * [在Python中有三元运算符吗?](part/3.md) 13 | * [Python中的元类(metaclass)是什么?](part/4.md) 14 | * [用Python如何一个文件是否存在?](part/5.md) 15 | * [在Python中调用外部命令?](part/6.md) 16 | * [如何在一个表达式里合并两个字典?](part/7.md) 17 | * [检查一个文件夹是否存在,如果不存在就创建它](part/8.md) 18 | * [在循环中获取索引(数组下标)](part/9.md) 19 | * [装饰器@staticmethod和@classmethod有什么区别?](part/10.md) 20 | * [Python中有检查字符串包含的方法吗?](part/11.md) 21 | * [在嵌套列表中获取 flat list](part/12.md) 22 | * [在Python中列出目录中的所有文件](part/13.md) 23 | * [用字典的值(key)对字典进行排序](part/14.md) 24 | * [理解Python切片](part/15.md) 25 | * [查找列表中某个元素的下标](part/16.md) 26 | * [检查列表是否为空的最好方法](part/17.md) 27 | * [使用 for 来迭代字典的原理](part/18.md) 28 | * [如何在一个函数里用全局变量?](part/19.md) 29 | * [Python中的appen和extend](part/20.md) 30 | * [在Python里获取当前时间](part/21.md) 31 | * [在一行里获取多个异常](part/22.md) 32 | * [`__str__`和`repr__`的区别](part/23.md) 33 | * [Python中如何在一个函数中加入多个装饰器?](part/24.md) 34 | * [在 Python 里如何手工进行延迟?](part/25.md) 35 | * [字典里添加元素的方法](part/26.md) 36 | * [检查一个键在字典中是否存在](part/27.md) 37 | * [怎么用引用来改变一个变量?](part/28.md) 38 | * [Python中的"小震撼":变化的默认参数](part/29.md) 39 | * [如何克隆或者 copy 一个 list ?](part/30.md) 40 | * [合并两个列表](part/31.md) 41 | * [理解Python中`super()`和`__init__()`方法](part/32.md) 42 | * [复制文件](part/33.md) 43 | * [怎么在windows下安装pip?](part/34.md) 44 | * [Python中`**`和`*`参数有什么用?](part/35.md) 45 | * [bytes 换成 string](part/36.md) 46 | * [`__init__.py` 的作用](part/37.md) 47 | * [在Python怎么样才能把列表分割成同样大小的块?](part/38.md) 48 | * [手动抛出异常](part/39.md) 49 | * [把字符串解析成浮点数或者整数](part/40.md) 50 | * [查找当前目录和文件目录](part/41.md) 51 | * [把字符串转化成时间](part/42.md) 52 | * [删除文件或者文件夹](part/43.md) 53 | * [怎么在终端里输出颜色?](part/44.md) 54 | * [获得一个字符串的子串](part/45.md) 55 | * [ 在 Python 中如何获取环境变量](part/46.md) 56 | * [为什么 "1000000000000000 in range(1000000000000001)" 在 Python3 里速度那么快?](part/47.md) 57 | * [如何改变 matplotlib 图像大小](part/48.md) 58 | * [获取列表最后一个元素](part/49.md) 59 | * [用pip升级所有包](part/50.md) 60 | * [有方法让Python运行在Android上吗?](part/51.md) 61 | * [在 Python 中如何将字符串转回为小写](part/52.md) 62 | * [](part/53.md) 63 | * [](part/54.md) 64 | * [把文件一行行读入数组](part/55.md) 65 | * [Python 中类的静态变量](part/56.md) 66 | * [怎么样获取一个列表的长度?](part/57.md) 67 | * [通过列表中字典的值对列表进行排序](part/58.md) 68 | * [](part/59.md) 69 | * [如何使打印的内容没有空格或换行](part/60.md) 70 | * [为什么在C++中读取stdin中的行会比Python慢呢?](part/61.md) 71 | * [ 在 Python 中如何移除字典中的 key ?](part/62.md) 72 | * [查看一个对象的类型](part/63.md) 73 | * [在列表中随机取一个元素](part/64.md) 74 | * [为什么是string.join(list)而不是list.join(string)?](part/65.md) 75 | * [通过函数名的字符串来调用这个函数](part/66.md) 76 | * [静态方法](part/67.md) 77 | * [Python中用什么代替switch语句?](part/68.md) 78 | * [限制浮点型到小数点后两位](part/69.md) 79 | * [如何移除换行符?](part/70.md) 80 | * [在 Python 中如何得到对象的所有属性?](part/71.md) 81 | * [在 macOS 上如何安装 pip](part/72.md) 82 | * [如何离开/退出/停用Python的virtualenv?](part/73.md) 83 | * [检查一个字符串是否是一个数字](part/74.md) 84 | * [ 如何查看 Python 变量的类型?](part/75.md) 85 | * [对于初学者如何理解 `@classmethod` 和 `@staticmethod`?](part/76.md) 86 | * [如何增加文件的内容?](part/77.md) 87 | * [如何在 .format 中使用大括号?](part/78.md) 88 | * [如何计算列表中元素出现的个数?](part/79.md) 89 | * [如何删除 list 中指定 index 的元素?](part/80.md) 90 | * [在 Python 里如何读取 stdin?](part/81.md) 91 | * [给字符串填充0](part/82.md) 92 | * [](part/83.md) 93 | * [如何获取实例的类名](part/84.md) 94 | * [](part/85.md) 95 | * [检查字符串为空的最优雅的方法](part/86.md) 96 | * [如何解析一个 JSON 文件?](part/87.md) 97 | * [`*args`和 `**kwargs`](part/88.md) 98 | * [](part/89.md) 99 | * [](part/90.md) 100 | * [整数转化为字符串](part/91.md) 101 | * [](part/92.md) 102 | * [输出到stderr](part/93.md) 103 | * [](part/94.md) 104 | * [反转字符串](part/95.md) 105 | * [生成包含大写字母和数字的随机字符串](part/96.md) 106 | * [字符串格式化:%和.format](part/97.md) 107 | * [](part/98.md) 108 | * [](part/99.md) 109 | * [](part/100.md) 110 | -------------------------------------------------------------------------------- /book.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Stackoverflow about Python", 3 | "description": "Stackoverflow 上关于 Python 的热门翻译", 4 | "author": "taizilongxu", 5 | "output.name": "site", 6 | "language": "zh-hans", 7 | "gitbook": "3.2.3", 8 | "root": ".", 9 | "plugins": [ 10 | "-lunr", 11 | "-search", 12 | "-highlight", 13 | "-livereload", 14 | "search-plus@^0.0.11", 15 | "simple-page-toc@^0.1.1", 16 | "github@^2.0.0", 17 | "github-buttons@2.1.0", 18 | "prism@^2.1.0", 19 | "prism-themes@^0.0.2", 20 | "advanced-emoji@^0.2.1", 21 | "anchors@^0.7.1", 22 | "include-codeblock@^3.0.2", 23 | "ace@^0.3.2", 24 | "emphasize@^1.1.0", 25 | "katex@^1.1.3", 26 | "splitter@^0.0.8", 27 | "mermaid-gb3@2.1.0", 28 | "tbfed-pagefooter@^0.0.1", 29 | "expandable-chapters-small@^0.1.7", 30 | "sectionx@^3.1.0", 31 | "local-video@^1.0.1", 32 | "anchor-navigation-ex@0.1.8", 33 | "favicon@^0.0.2", 34 | "todo@^0.1.3", 35 | "3-ba@^0.9.0", 36 | "terminal@^0.3.2", 37 | "alerts@^0.2.0", 38 | "include-csv@^0.1.0", 39 | "puml@^1.0.1", 40 | "musicxml@^1.0.2", 41 | "klipse@^1.2.0", 42 | "versions-select@^0.1.1", 43 | "-sharing", 44 | "sharing-plus@^0.0.2", 45 | "graph@^0.1.0", 46 | "chart@^0.2.0" 47 | ], 48 | 49 | "pluginsConfig": { 50 | "github-buttons": { 51 | "buttons": [ 52 | { 53 | "user": "taizilongxu", 54 | "repo": "stackoverflow_python", 55 | "type": "star", 56 | "size": "small" 57 | } 58 | ] 59 | }, 60 | "theme-default": { 61 | "showLevel": true 62 | }, 63 | "github": { 64 | "url": "https://github.com/taizilongxu/stackoverflow_python" 65 | }, 66 | "include-codeblock": { 67 | "template": "ace", 68 | "unindent": true, 69 | "edit": true 70 | }, 71 | "sharing": { 72 | "douban": false, 73 | "facebook": false, 74 | "google": true, 75 | "hatenaBookmark": false, 76 | "instapaper": false, 77 | "line": false, 78 | "linkedin": true, 79 | "messenger": false, 80 | "pocket": false, 81 | "qq": false, 82 | "qzone": false, 83 | "stumbleupon": false, 84 | "twitter": false, 85 | "viber": false, 86 | "vk": false, 87 | "weibo": true, 88 | "whatsapp": false, 89 | "all": [ 90 | "facebook", "google", "twitter", 91 | "weibo", "instapaper", "linkedin", 92 | "pocket", "stumbleupon", "qq", "qzone" 93 | ] 94 | }, 95 | "tbfed-pagefooter": { 96 | "copyright": "Copyright © taizilongxu 2018", 97 | "modify_label": "该文件修订时间:", 98 | "modify_format": "YYYY-MM-DD HH:mm:ss" 99 | }, 100 | "3-ba": { 101 | "token": "ff100361cdce95dd4c8fb96b4009f7bc" 102 | }, 103 | "simple-page-toc": { 104 | "maxDepth": 3, 105 | "skipFirstH1": true 106 | }, 107 | "anchor-navigation-ex": { 108 | "isRewritePageTitle": false, 109 | "tocLevel1Icon": "fa fa-hand-o-right", 110 | "tocLevel2Icon": "fa fa-hand-o-right", 111 | "tocLevel3Icon": "fa fa-hand-o-right" 112 | }, 113 | "sectionx": { 114 | "tag": "b" 115 | }, 116 | "favicon": { 117 | "shortcut": "favicon.ico", 118 | "bookmark": "favicon.ico" 119 | }, 120 | "terminal": { 121 | "copyButtons": true, 122 | "fade": false, 123 | "style": "flat" 124 | } 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /data/101754.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 有方法让Python运行在Android上吗? 4 | 5 | 我喜欢Android平台.试试上我和几个朋友在Spoxt项目里在用ADC(数模转换器?) 6 | 7 | 但是我一点也不喜欢Java.我们工作在S60版本而且一个不错的Python的API.我知道Android上没有官方的Python版本,但是既然有Jython,有没有什么方法让它们能在Android上工作? 8 | 9 | *** 10 | 11 | 有一种方法,使用[Kivy](http://kivy.org/): 12 | 13 | ``` 14 | 交互界面快速开发应用的Python开源库,像多点触控app. 15 | ``` 16 | 17 | ``` 18 | Kivy运行在 Linux, Windows, OS X, Android and iOS.你也可以在所有的平台上运行Python代码 19 | ``` 20 | 21 | [Kivy的应用](https://play.google.com/store/apps/details?id=org.kivy.showcase) 22 | 23 | -------------------------------------------------------------------------------- /data/1024847.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 字典里添加元素的方法 4 | 5 | 当一个字典被创建了,能不能在字典里计入一个键?好像没有`.add()`的方法. 6 | 7 | *** 8 | 9 | ```python 10 | >>> d = {'key':'value'} 11 | >>> print d 12 | {'key': 'value'} 13 | >>> d['mynewkey'] = 'mynewvalue' 14 | >>> print d 15 | {'mynewkey': 'mynewvalue', 'key': 'value'} 16 | ``` 17 | 18 | *** 19 | 20 | ```python 21 | >>> x = {1:2} 22 | >>> print x 23 | {1: 2} 24 | 25 | >>> x.update({3:4}) 26 | >>> print x 27 | {1: 2, 3: 4} 28 | ``` -------------------------------------------------------------------------------- /data/11241523.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 为什么代码在一个函数里运行的更快? 4 | 5 | ```python 6 | def main(): 7 | for i in xrange(10**8): 8 | pass 9 | main() 10 | ``` 11 | 12 | 在Python中运行速度: 13 | 14 | ```python 15 | real 0m1.841s 16 | user 0m1.828s 17 | sys 0m0.012s 18 | ``` 19 | 20 | 然而不把它放在函数里: 21 | 22 | ```python 23 | for i in xrange(10**8): 24 | pass 25 | ``` 26 | 27 | 它比上一个运行时间更长 28 | 29 | ```python 30 | real 0m4.543s 31 | user 0m4.524s 32 | sys 0m0.012s 33 | ``` 34 | 35 | 为啥会这样? 36 | 37 | 注:这个计时是用LinuxBASH中的时间函数. 38 | 39 | *** 40 | 41 | 你或许想问为什么存取一个本地变量比全局变量要快.这有关于CPython的实现细节. 42 | 43 | 记住CPython解析器运行的是被编译过的字节编码(bytecode).当一个函数被编译后,局部变量被存储在了固定大小的数组(不是一个`dict`),而变量名赋值给了索引.这就是为什么你不能动态的为一个函数添加局部变量.检查一个局部变量就好像是一个指针去查找列表,对于在`PyObject`上的引用计数的增长是微不足道的. 44 | 45 | 相反的在查找全局变量(`LOAD_GLOBAL`)时,涉及到的是一个实实在在的`dict`的哈希查找.顺便说一句,这就是为什么当你想要一个全局变量你必须要在前面加上`global i`:如果你在一个区域内指定一个变量,编译器就会建立一个`STORE_FAST`的入口,除非你不让它那么做. 46 | 47 | 在说一句,全局查找速度也不慢.真正拖慢速度的是像`foo.bar`这样的属性查找! 48 | 49 | *** 50 | 51 | 在一个函数里,字节码是这样的: 52 | 53 | ```python 54 | 2 0 SETUP_LOOP 20 (to 23) 55 | 3 LOAD_GLOBAL 0 (xrange) 56 | 6 LOAD_CONST 3 (100000000) 57 | 9 CALL_FUNCTION 1 58 | 12 GET_ITER 59 | >> 13 FOR_ITER 6 (to 22) 60 | 16 STORE_FAST 0 (i) 61 | 62 | 3 19 JUMP_ABSOLUTE 13 63 | >> 22 POP_BLOCK 64 | >> 23 LOAD_CONST 0 (None) 65 | 26 RETURN_VALUE 66 | ``` 67 | 68 | 如果在全局,字节码: 69 | 70 | ```python 71 | 1 0 SETUP_LOOP 20 (to 23) 72 | 3 LOAD_NAME 0 (xrange) 73 | 6 LOAD_CONST 3 (100000000) 74 | 9 CALL_FUNCTION 1 75 | 12 GET_ITER 76 | >> 13 FOR_ITER 6 (to 22) 77 | 16 STORE_NAME 1 (i) 78 | 79 | 2 19 JUMP_ABSOLUTE 13 80 | >> 22 POP_BLOCK 81 | >> 23 LOAD_CONST 2 (None) 82 | 26 RETURN_VALUE 83 | ``` 84 | 85 | 两者的区别是[`STORE_FAST`](http://docs.python.org/library/dis.html#opcode-STORE_FAST)比[`STORE_NAME`](http://docs.python.org/library/dis.html#opcode-STORE_NAME)要快很多.这是因为在函数里`i`是一个局部变量而在全局区域它是一个全局变量. 86 | 87 | 可以看一下字节编码,用到了[`dis`](http://docs.python.org/library/dis.html)模块.我可以直接解析函数,但是要解析全局代码必须用[`compile`](http://docs.python.org/library/functions.html#compile)内建模块. -------------------------------------------------------------------------------- /data/11277432.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在 Python 中如何移除字典中的 key ? 4 | 5 | 当我想移除字典里的 key 时: 6 | 7 | ```python 8 | if 'key' in myDict: 9 | del myDict['key'] 10 | ``` 11 | 12 | 有没有一行就能实现的代码? 13 | 14 | *** 15 | 16 | 用 [dict.pop()](http://docs.python.org/library/stdtypes.html#dict.pop) 17 | 18 | ```python 19 | my_dict.pop('key', None) 20 | ``` 21 | 22 | 上面的代码如果 `key` 存在将会返回 `my_dict[key]`, 不存在就会返回 `None`.如果第二个参数没有指定(例如, `my_dict.pop('key')`),那么如果 `key` 不存在就会抛出 `KeyError` 异常. -------------------------------------------------------------------------------- /data/1132941.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## Python中的"小震撼":变化的默认参数 4 | 5 | 许多 Python 老手也被下面的问题困扰: 6 | 7 | ```python 8 | def foo(a=[]): 9 | a.append(5) 10 | return a 11 | ``` 12 | 13 | Python 新手估计可能会想这个函数返回一个只有元素`[5]`的列表.但是结果却出人意料: 14 | 15 | ```python 16 | >>> foo() 17 | [5] 18 | >>> foo() 19 | [5, 5] 20 | >>> foo() 21 | [5, 5, 5] 22 | >>> foo() 23 | [5, 5, 5, 5] 24 | >>> foo() 25 | ``` 26 | 27 | 我的一个经理曾经碰到过这个特性并把它叫做语言的"动态设计缺陷". 这个现象应当有更深层次的解释, 如果你不懂它的内部它确实非常令人困惑. 然而我不能回答下面的问题:是什么原因使默认参数在函数的定义时被绑定,而不是在执行时?我怀疑这个特性在现实中有没有实际的用途(就像在C语言中有谁去用静态变量?) 28 | 29 | *** 30 | 31 | 事实上这并不是设计缺陷,也不是什么内部或性能原因. 32 | 33 | 原因很简单,Python中的函数是最高等级的对象,而不仅仅是一小段代码. 34 | 35 | 试着这么来理解:**一个函数是一个被它自己定义而执行的对象;默认参数是一种"成员数据",所以它们的状态和其他对象一样,会随着每一次调用而改变.** 36 | 37 | Effbot在它的[Python中的默认参数](http://effbot.org/zone/default-values.htm)对这种行为的原因解释的非常清楚!我强烈建议你读一读能对函数对象的工作原理有更深一步的了解. 38 | 39 | 40 | 41 | 42 | ## Python 中的默认参数(文章翻译) 43 | 44 | Python 默认参数很容易让新手犯错. 45 | 46 | 引起错误的原因通常是使用可变(mutable)对象作为了参数的默认值, 这个可变对象是可以被修改的, 比如说列表(list)和字典(dict) 47 | 48 | 例如: 49 | ```python 50 | >>> def function(data=[]): 51 | ... data.append(1) 52 | ... return data 53 | ... 54 | >>> function() 55 | [1] 56 | >>> function() 57 | [1, 1] 58 | >>> function() 59 | [1, 1, 1] 60 | ``` 61 | 62 | 可以看到上面的列表(list)越来越长, 如果检查这个列表的id, 会发现他返回的是同一个值: 63 | 64 | ```python 65 | >>> id(function()) 66 | 12516768 67 | >>> id(function()) 68 | 12516768 69 | >>> id(function()) 70 | 12516768 71 | ``` 72 | 73 | 原因很简单: 在每次函数调用的时候都使用同一个对象(object), 这个可修改的特性我们叫做 "sticky". 74 | 75 | ### 原理 76 | 77 | 只有当"def"语句执行的时候才会对默认参数值进行赋值, 可以看看文档的定义: 78 | 79 | https://docs.python.org/2.0/ref/function.html 80 | 81 | 还要注意的是在Python 中 "def" 是可执行语句, 默认参数仅在"def" 语句环境里生效.每次执行"def"语句都会创建一个新的函数对象(每次都会对默认参数进行赋值) 82 | -------------------------------------------------------------------------------- /data/1185524.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 怎么样去除空格(包括tab)? 4 | 5 | 有什么函数既可以去掉空格也能去掉tab? 6 | 7 | *** 8 | 9 | 在两侧的空白: 10 | 11 | ```python 12 | s = " \t a string example\t " 13 | s = s.strip() 14 | ``` 15 | 16 | 右边的空白: 17 | 18 | ```python 19 | s = s.rstrip() 20 | ``` 21 | 22 | 左边的空白: 23 | 24 | ```python 25 | s = s.lstrip() 26 | ``` 27 | 28 | 也可以指定字符来去除: 29 | 30 | ```python 31 | s = s.strip(' \t\n\r') 32 | ``` 33 | 34 | 上面的将会去掉在`s`左右的空白,\t,\n和\r字符. -------------------------------------------------------------------------------- /data/12179271.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 对于初学者如何理解 `@classmethod` 和 `@staticmethod`? 4 | 5 | 6 | *** 7 | 8 | 虽然 `classmethod` 和 `staticmethod` 非常接近, 但是用途却是不同: `classmethod` 必须把类对象的引用作为第一个参数,而 `staticmethod` 则不需要. 9 | 10 | ### 例子 11 | 12 | ```python 13 | class Date(object): 14 | 15 | def __init__(self, day=0, month=0, year=0): 16 | self.day = day 17 | self.month = month 18 | self.year = year 19 | 20 | @classmethod 21 | def from_string(cls, date_as_string): 22 | day, month, year = map(int, date_as_string.split('-')) 23 | date1 = cls(day, month, year) 24 | return date1 25 | 26 | @staticmethod 27 | def is_date_valid(date_as_string): 28 | day, month, year = map(int, date_as_string.split('-')) 29 | return day <= 31 and month <= 12 and year <= 3999 30 | 31 | date2 = Date.from_string('11-09-2012') 32 | is_date = Date.is_date_valid('11-09-2012') 33 | ``` 34 | 35 | ### 解释 36 | 37 | 让我们来创建一个处理日期的 class: 38 | 39 | ```python 40 | class Date(object): 41 | 42 | def __init__(self, day=0, month=0, year=0): 43 | self.day = day 44 | self.month = month 45 | self.year = year 46 | ``` 47 | 48 | 这个 class 很显然是用来存储特定日期的信息. 49 | 50 | 这里用 Python 的 `__init__` 来初始化类实例, 它可以接收参数作为一个 `instancemethod`, 它的第一个参数 `self` 是新建实例的引用. 51 | 52 | #### 类方法 53 | 54 | 我们可以用 `classmethod` 来很好的完成一些功能. 55 | 56 | 假设我们想通过一些形如 `dd-mm-yyyy` 的 string 来创建 `Date` 实例.而且我们需要在我们工程里许多不同的地方实现. 57 | 58 | 所以我们必须: 59 | 60 | 1. 解析 string 为天,月和年这3个整数或者3元元祖. 61 | 2. 通过传递这些值来完成 `Date` 的初始化调用 62 | 63 | ```python 64 | day, month, year = map(int, string_date.split('-')) 65 | date1 = Date(day, month, year) 66 | ``` 67 | 68 | 在 C++ 里可以用 overloading 的方法来实现, 但是 Python 里没有 overloading.取而代之的我们可以使用 `classmethod`.让我们来创建另一种 `constructor` 69 | 70 | ```python 71 | @classmethod 72 | def from_string(cls, date_as_string): 73 | day, month, year = map(int, date_as_string.split('-')) 74 | date1 = cls(day, month, year) 75 | return date1 76 | 77 | date2 = Date.from_string('11-09-2012') 78 | ``` 79 | 80 | 让我们仔细看看上面两个实现,来看看两个实现的优缺点: 81 | 82 | 1. 我们在一个地方实现了 date string 的转换并且可以复用. 83 | 2. 很好的封装(如果你认为或许可以实现一个函数来解析, 但是这么做更符合 OOP 设计) 84 | 3. `cls` 是一个承载 class 自己的对象, 并不是 class 的实例.这个非常好用,因为只要我们继承了 `Data` class, 所有的子类都拥有 `from_string` 这个方法. 85 | 86 | #### 静态方法 87 | 88 | `staticmethods` 呢?它非常像 `classmethod` 但是它不包含任何必须的参数(比如说类方法或者实例方法). 89 | 90 | 让我们看看下一个用法. 91 | 92 | 我们想验证一个 date string 的有效性,这个任务不需要绑定到实例上只需要绑定到类上面. 93 | 94 | `staticmethod` 对我们来说就比较好用了.我们看看下一段代码: 95 | 96 | ```python 97 | @staticmethod 98 | def is_date_valid(date_as_string): 99 | day, month, year = map(int, date_as_string.split('-')) 100 | return day <= 31 and month <= 12 and year <= 3999 101 | 102 | # usage: 103 | is_date = Date.is_date_valid('11-09-2012') 104 | ``` 105 | 106 | 所以我们看到 `staticmethod` 就想一个函数一样不需要指定 class,语法上的调用也非常像函数,没办法访问对象及其内部,而 `classmethod` 就可以. -------------------------------------------------------------------------------- /data/1231688.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何移除用easy_install下载的包? 4 | 5 | 用`easy_install`下载包非常方便.但是我至今没发现怎么移除下载的包. 6 | 7 | 有什么更好的方法来移除包?如果我手动移除的话需要修改什么文件?(比如`rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg`) 8 | 9 | *** 10 | 11 | [pip](http://pypi.python.org/pypi/pip/),另一个选择,提供了"uninstall"命令. 12 | 13 | 按着[说明](http://pip.readthedocs.org/en/latest/installing.html)安装pip: 14 | 15 | ``` 16 | $ wget https://bootstrap.pypa.io/get-pip.py 17 | $ python get-pip.py 18 | ``` 19 | 20 | 然后就可以用`pip uninstall`去移除用`easy_install`安装的包. -------------------------------------------------------------------------------- /data/123198.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 复制文件 4 | 5 | 怎么在Python里赋值文件?在`os`下没找到复制的方法. 6 | 7 | [`shutil`](http://docs.python.org/2/library/shutil.html)有许多的方法.其中之一就是: 8 | 9 | ```python 10 | copyfile(src, dst) 11 | ``` 12 | 13 | 把`src`文件的内容复制给`dst`.目的地址必须是可写的;否则将会出现`IOError`错误.如果`dst`已经存在,将会被覆盖.一些像字符或者块设备不能用这个方法赋值.`src`和`dst`是路径名的字符串形式. -------------------------------------------------------------------------------- /data/1301346.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在实例名字前单下划线和双下划线的含义 4 | 5 | 我想刨根问底,这到底是什么意思?解释一下他俩的区别. 6 | 7 | *** 8 | 9 | ### 单下划线 10 | 11 | 在一个类中的方法或属性用单下划线开头就是告诉别的程序这个属性或方法是私有的.然而对于这个名字来说并没有什么特别的. 12 | 13 | 引自[PEP-8](http://www.python.org/dev/peps/pep-0008/): 14 | 15 | 16 | >单下划线:"内部使用"的弱指示器.比如,from M import * 将不会引进用但下划线开头的对象. 17 | 18 | ### 双下划线 19 | 20 | 来自[Python文档](http://docs.python.org/tutorial/classes.html#private-variables-and-class-local-references): 21 | 22 | 23 | >任何`__spam`形式(至少两个下划线开头,至多一个下划线结尾)都是代替`_classname__spam`,其中classname是当前类的名字.This mangling is done without regard to the syntactic position of the identifier.所以它能用来定义私有类的实例和类变量,方法,在全局中的变量,甚至是实例中的变量.可以区别不同类的实例. 24 | 25 | 26 | ### 例子 27 | 28 | ```Python 29 | >>> class MyClass(): 30 | ... def __init__(self): 31 | ... self.__superprivate = "Hello" 32 | ... self._semiprivate = ", world!" 33 | ... 34 | >>> mc = MyClass() 35 | >>> print mc.__superprivate 36 | Traceback (most recent call last): 37 | File "", line 1, in 38 | AttributeError: myClass instance has no attribute '__superprivate' 39 | >>> print mc._semiprivate 40 | , world! 41 | >>> print mc.__dict__ 42 | {'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'} 43 | ``` 44 | 45 | *** 46 | 47 | `__foo__`:一种约定,Python内部的名字,用来区别其他用户自定义的命名,以防冲突. 48 | 49 | `_foo`:一种约定,用来指定变量私有.程序员用来指定私有变量的一种方式. 50 | 51 | `__foo`:这个有真正的意义:解析器用`_classname__foo`来代替这个名字,以区别和其他类相同的命名. 52 | 53 | 在Python中没有其他形式的下划线了. 54 | 55 | 这种约定方式和类,变量,全局变量等没有区别. -------------------------------------------------------------------------------- /data/136097.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 装饰器@staticmethod和@classmethod有什么区别? 4 | 5 | *** 6 | 7 | 也许一些例子会有帮助:注意`foo`, `class_foo` 和`static_foo`参数的区别: 8 | 9 | ```python 10 | class A(object): 11 | def foo(self,x): 12 | print "executing foo(%s,%s)"%(self,x) 13 | 14 | @classmethod 15 | def class_foo(cls,x): 16 | print "executing class_foo(%s,%s)"%(cls,x) 17 | 18 | @staticmethod 19 | def static_foo(x): 20 | print "executing static_foo(%s)"%x 21 | 22 | a=A() 23 | ``` 24 | 25 | 下面是一个对象实体调用方法的常用方式.对象实体`a`被隐藏的传递给了第一个参数. 26 | 27 | ```python 28 | a.foo(1) 29 | # executing foo(<__main__.A object at 0xb7dbef0c>,1) 30 | ``` 31 | 32 | 用**classmethods**装饰,隐藏的传递给第一个参数的是对象实体的类(`class A`)而不是`self`. 33 | 34 | ```python 35 | a.class_foo(1) 36 | # executing class_foo(,1) 37 | ``` 38 | 39 | 你也可以用类调用`class_foo`.实际上,如果你把一些方法定义成`classmethod`,那么实际上你是希望用类来调用这个方法,而不是用这个类的实例来调用这个方法.`A.foo(1)`将会返回一个`TypeError`错误,` A.class_foo(1)`将会正常运行: 40 | 41 | ```python 42 | A.class_foo(1) 43 | # executing class_foo(,1) 44 | ``` 45 | 46 | One use people have found for class methods is to create inheritable alternative constructors. 47 | 48 | 用**staticmethods**来装饰,不管传递给第一个参数的是`self`(对象实体)还是`cls`(类).它们的表现都一样: 49 | 50 | ```python 51 | a.static_foo(1) 52 | # executing static_foo(1) 53 | 54 | A.static_foo('hi') 55 | # executing static_foo(hi) 56 | ``` 57 | 58 | 静态方法被用来组织类之间有逻辑关系的函数. 59 | 60 | `foo`只是个函数,但是当你调用`a.foo`的时候你得到的不仅仅是一个函数,你得到的是一个第一个参数绑定到`a`的"加强版"函数.`foo`需要两个参数,而`a.foo`仅仅需要一个参数. 61 | 62 | `a`绑定了`foo`.下面可以知道什么叫"绑定"了: 63 | 64 | ```python 65 | print(a.foo) 66 | # > 67 | ``` 68 | 69 | 如果使用`a.class_foo`,是`A`绑定到了`class_foo`而不是`a`. 70 | 71 | ```python 72 | print(a.class_foo) 73 | # > 74 | ``` 75 | 76 | 最后剩下静态方法,说到底它就是一个方法.`a.static_foo`只是返回一个不带参数绑定的方法.`static_foo`和`a.static_foo`只需要一个参数. 77 | 78 | ```python 79 | print(a.static_foo) 80 | # 81 | ``` -------------------------------------------------------------------------------- /data/1436703.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## `__str__`和`repr__`的区别 4 | 5 | `__str__`和`repr__`有什么区别? 6 | 7 | *** 8 | 9 | 首先让我们梳理一下张三的答案: 10 | 11 | * 用起来没有什么区别 12 | * `__repr__`的目的是明确的 13 | * `__str__`的目的是可读性 14 | * `__str__`的用法包含`__repr__` 15 | 16 | #### 用法没有什么区别 17 | 18 | 因为Python的宗旨是易用的,所以这看起来有点不寻常.但是当 -------------------------------------------------------------------------------- /data/1450393.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在 Python 里如何读取 stdin? 4 | 5 | *** 6 | 7 | 可以使用 [`fileinput`](http://docs.python.org/library/fileinput.html): 8 | 9 | ```python 10 | import fileinput 11 | 12 | for line in fileinput.input(): 13 | pass 14 | ``` 15 | 16 | [`fileinput`](http://docs.python.org/library/fileinput.html) 命令可以迭代命令参数给出的文件的每一行, 如果没有给出参数则直接从标准输入中得到. -------------------------------------------------------------------------------- /data/1602934.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 检查一个键在字典中是否存在 4 | 5 | 在更新字典之前想检查键是否存在.我写了如下代码: 6 | 7 | ```python 8 | if 'key1' in dict.keys(): 9 | print "blah" 10 | else: 11 | print "boo" 12 | ``` 13 | 14 | 我想这不是最好的方法,还有什么更好的方法? 15 | 16 | *** 17 | 18 | 用`in`. 19 | 20 | ```python 21 | d = dict() 22 | 23 | for i in xrange(100): 24 | key = i % 10 25 | if key in d: 26 | d[key] += 1 27 | else: 28 | d[key] = 1 29 | ``` 30 | 31 | 如果你想要一个默认值,你可以用`dict.get()`: 32 | 33 | ```python 34 | d = dict() 35 | 36 | for i in xrange(100): 37 | key = i % 10 38 | d[key] = d.get(key, 0) + 1 39 | ``` 40 | 41 | 如果相对所有值设置默认值可以用`collections`模块的`defaultdict`函数: 42 | 43 | ```python 44 | from collections import defaultdict 45 | 46 | d = defaultdict(lambda: 0) 47 | 48 | for i in xrange(100): 49 | d[i % 10] += 1 50 | ``` 51 | 52 | 但是总而言之`in`是最好的方法. -------------------------------------------------------------------------------- /data/1712227.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 怎么样获取一个列表的长度? 4 | 5 | ```python 6 | items = [] 7 | items.append("apple") 8 | items.append("orange") 9 | items.append("banana") 10 | 11 | # FAKE METHOD:: 12 | items.amount() # 返回 3 13 | ``` 14 | 15 | 怎么样做才对? 16 | 17 | *** 18 | 19 | [len](https://docs.python.org/2/library/functions.html#len)函数可以用于Python中许多的类型,包括内建类型和标准库类型. 20 | 21 | ```python 22 | >>len([1,2,3]) 23 | 3 24 | ``` -------------------------------------------------------------------------------- /data/1720421.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 合并两个列表 4 | 5 | 怎样合并两个列表? 6 | 7 | 例如: 8 | 9 | ```python 10 | listone = [1,2,3] 11 | listtwo = [4,5,6] 12 | ``` 13 | 14 | 我期待: 15 | 16 | ```python 17 | mergedlist == [1, 2, 3, 4, 5, 6] 18 | ``` 19 | 20 | *** 21 | 22 | 在Python中非常容易. 23 | 24 | ```python 25 | mergedlist = listone + listtwo 26 | ``` -------------------------------------------------------------------------------- /data/17271319.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在 macOS 上如何安装 pip 4 | 5 | 昨天我花了许多时间研究怎么安装 `pip`, 但是没有找到方法 6 | 7 | 我该怎么安装它? 8 | 9 | *** 10 | 11 | ```python 12 | easy_install pip 13 | ``` 14 | 15 | 如果你需要管理员权限, 试一下: 16 | 17 | ```python 18 | sudo easy_install pip 19 | ``` -------------------------------------------------------------------------------- /data/1747817.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 使用列表推导式的方式来创建字典 4 | 5 | *** 6 | 7 | 在 Python2.6 或者之前的版本: 8 | 9 | ```python 10 | d = dict((key, value) for (key, value) in iterable 11 | ``` 12 | 13 | 在 Python2.7 和 3以后的版本中, 你可以直接使用 [dict comprehension syntax](http://www.python.org/dev/peps/pep-0274/): 14 | 15 | ```python 16 | d = {key: value for (key, value) in iterable} 17 | ``` 18 | 19 | 当然你可以使用任何包含两个元素的迭代方式来进行生成: 20 | 21 | ```python 22 | d = {value: foo(value) for value in sequence if bar(value)} 23 | 24 | def key_value_gen(k): 25 | yield chr(k+65) 26 | yield chr((k+13)%26+65) 27 | d = dict(map(key_value_gen, range(26))) 28 | ``` -------------------------------------------------------------------------------- /data/176918.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 查找列表中某个元素的下标 4 | 5 | 比如`["foo","bar","baz"]`和它的一个元素`"bar"`,用什么方法能找到它的下标(1)? 6 | 7 | *** 8 | 9 | ```python 10 | >>> ["foo","bar","baz"].index('bar') 11 | 1 12 | ``` 13 | 14 | 参考资料:[Data Structures > More on Lists](http://docs.python.org/2/tutorial/datastructures.html#more-on-lists) -------------------------------------------------------------------------------- /data/1952464.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在Python中如何判断一个对象是可迭代的? 4 | 5 | 有没有一个`isiterable`的方法?我找到的解决方法: 6 | 7 | ```python 8 | hasattr(myObj, '__iter__') 9 | ``` 10 | 11 | 但是我不知道这是不是最好的. 12 | 13 | *** 14 | 15 | ### 鸭子类型 16 | 17 | ```python 18 | try: 19 | iterator = iter(theElement) 20 | except TypeError: 21 | # not iterable 22 | else: 23 | # iterable 24 | 25 | # for obj in iterator: 26 | # pass 27 | ``` 28 | 29 | ### 类型检查 30 | 31 | 用[抽象基类](http://docs.python.org/library/abc.html).至少Python2.6以上而且只针对新式类. 32 | 33 | ```python 34 | import collections 35 | 36 | if isinstance(theElement, collections.Iterable): 37 | # iterable 38 | else: 39 | # not iterable 40 | ``` -------------------------------------------------------------------------------- /data/2052390.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 手动抛出异常 4 | 5 | 我想故意制造一个错误,所以我可以转到`excepy:`语句 6 | 7 | 我怎么做? 8 | 9 | *** 10 | 11 | 不能在Pythonic了; 12 | 13 | ```python 14 | raise Exception("I know python!") 15 | ``` 16 | 17 | 想得到更多信息,看[这里](http://docs.python.org/reference/simple_stmts.html#the-raise-statement) -------------------------------------------------------------------------------- /data/2225038.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 查看一个对象的类型 4 | 5 | 有什么方便的方法查看一个对象的类型? 6 | 7 | *** 8 | 9 | 为了获得对象的类型,可以用内建函数`type()`.把对象作为唯一的参数传递将会返回这个对象的类型: 10 | 11 | ```python 12 | >>> type([]) is list 13 | True 14 | >>> type({}) is dict 15 | True 16 | >>> type('') is str 17 | True 18 | >>> type(0) is int 19 | True 20 | ``` 21 | 22 | 当然也对自定义类型也有用: 23 | 24 | ```python 25 | >>> class Test1 (object): 26 | pass 27 | >>> class Test2 (Test1): 28 | pass 29 | >>> a = Test1() 30 | >>> b = Test2() 31 | >>> type(a) is Test1 32 | True 33 | >>> type(b) is Test2 34 | True 35 | ``` 36 | 37 | 注意`type()`只会返回对象的直接类型,不会告诉你继承类型. 38 | 39 | ```python 40 | >>> type(b) is Test1 41 | False 42 | ``` 43 | 44 | 可以用`isinstance`函数.也对内建函数管用: 45 | 46 | ```python 47 | >>> isinstance(b, Test1) 48 | True 49 | >>> isinstance(b, Test2) 50 | True 51 | >>> isinstance(a, Test1) 52 | True 53 | >>> isinstance(a, Test2) 54 | False 55 | >>> isinstance([], list) 56 | True 57 | >>> isinstance({}, dict) 58 | True 59 | ``` 60 | 61 | `isinstance()`通常是确定一个对象类型更好的方法,因为它接受派生类型.所以除非你确实需要知道对象的类型(一些其他原因),用`isinstance()`比`type()`更好. 62 | 63 | `isinstance()`的第二个参数也接受类型的元组,所以也可以一次检查多种类型.如果是这些类型里的`isinstance()`将会返回true: 64 | 65 | ```python 66 | >>> isinstance([], (tuple, list, set)) 67 | True 68 | ``` -------------------------------------------------------------------------------- /data/2257441.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 生成包含大写字母和数字的随机字符串 4 | 5 | 我希望生成N大小的字符串. 6 | 7 | 里面只含有数字和大写字母,比如: 8 | 9 | * 6U1S75 10 | * 4Z4UKK 11 | * U911K4 12 | 13 | 有没有什么[Pythonic](https://en.wikipedia.org/wiki/Python_%28programming_language%29#Features_and_philosophy)的方法? 14 | 15 | *** 16 | 17 | 一行写的答案: 18 | 19 | ```python 20 | ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) 21 | ``` 22 | 23 | 为了重用可以这样写: 24 | 25 | ```python 26 | >>> import string 27 | >>> import random 28 | >>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits): 29 | ... return ''.join(random.choice(chars) for _ in range(size)) 30 | ... 31 | >>> id_generator() 32 | 'G5G74W' 33 | >>> id_generator(3, "6793YUIO") 34 | 'Y3U' 35 | ``` 36 | 37 | #### 如何工作? 38 | 39 | 我们引入`string`和`random`模块,`string`模块包含了所有常用的ASCII字符,`random`模块处理随机数的生成. 40 | 41 | `string.ascii_uppercase + string.digits`是一个包含大写字母和数字的列表: 42 | 43 | ```python 44 | >>> string.ascii_uppercase 45 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 46 | >>> string.digits 47 | '0123456789' 48 | >>> string.ascii_uppercase + string.digits 49 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' 50 | ``` 51 | 52 | 然后我们用列表推导式创建`n`个元素的列表: 53 | 54 | ```python 55 | >>> range(4) # n个数字的列白哦 56 | [0, 1, 2, 3] 57 | >>> ['elem' for _ in range(4)] # 在一个列表创建4次'elem' 58 | ['elem', 'elem', 'elem', 'elem'] 59 | ``` 60 | 61 | 在上面的例子中,我们用`[]`来创建列表,和`id_generator`函数不一样,生成器不再内存中创建列表,只是在程序运行时一个一个的生成列表元素(更多见[这里](http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained/231855#231855)) 62 | 63 | 下面是在列表中随机取出一个元素: 64 | 65 | ```python 66 | >>> random.choice("abcde") 67 | 'a' 68 | >>> random.choice("abcde") 69 | 'd' 70 | >>> random.choice("abcde") 71 | 'b' 72 | ``` 73 | 74 | 所以`random.choice(chars) for _ in range(size)`会取出`size`个字符.字符随机的在`chars`中取出: 75 | 76 | ```python 77 | >>> [random.choice('abcde') for _ in range(3)] 78 | ['a', 'b', 'b'] 79 | >>> [random.choice('abcde') for _ in range(3)] 80 | ['e', 'b', 'e'] 81 | >>> [random.choice('abcde') for _ in range(3)] 82 | ['d', 'a', 'c'] 83 | ``` 84 | 85 | 然后我们可以用空字符串把它们连起来成为一个字符串: 86 | 87 | ```python 88 | >>> ''.join(['a', 'b', 'b']) 89 | 'abb' 90 | >>> [random.choice('abcde') for _ in range(3)] 91 | ['d', 'c', 'b'] 92 | >>> ''.join(random.choice('abcde') for _ in range(3)) 93 | 'dac' 94 | ``` -------------------------------------------------------------------------------- /data/231767.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | 4 | ## Python中关键字yield有什么作用? 5 | 6 | yield有什么用? 7 | 8 | 例如下面这段代码: 9 | 10 | ```python 11 | def node._get_child_candidates(self, distance, min_dist, max_dist): 12 | if self._leftchild and distance - max_dist < self._median: 13 | yield self._leftchild 14 | if self._rightchild and distance + max_dist >= self._median: 15 | yield self._rightchild 16 | ``` 17 | 18 | 下面是调用它: 19 | 20 | ```python 21 | result, candidates = list(), [self] 22 | while candidates: 23 | node = candidates.pop() 24 | distance = node._get_dist(obj) 25 | if distance <= max_dist and distance >= min_dist: 26 | result.extend(node._values) 27 | candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) 28 | return result 29 | ``` 30 | 31 | 当`_get_child_candidates`方法被调用的时候发生了什么?是返回一个列表?还是一个元祖?它还能第二次调用吗?后面的调用什么时候结束? 32 | 33 | *** 34 | 35 | 为了理解yield有什么用,首先得理解generators,而理解generators前还要理解iterables 36 | 37 | #### Iterables 38 | 39 | 当你创建了一个列表,你可以一个一个的读取它的每一项,这叫做iteration: 40 | 41 | ```python 42 | >>> mylist = [1, 2, 3] 43 | >>> for i in mylist: 44 | ... print(i) 45 | 1 46 | 2 47 | 3 48 | ``` 49 | 50 | Mylist是可迭代的.当你用列表推导式的时候,你就创建了一个列表,而这个列表也是可迭代的: 51 | 52 | ```python 53 | >>> mylist = [x*x for x in range(3)] 54 | >>> for i in mylist: 55 | ... print(i) 56 | 0 57 | 1 58 | 4 59 | ``` 60 | 61 | 所有你可以用在`for...in...`语句中的都是可迭代的:比如lists,strings,files...因为这些可迭代的对象你可以随意的读取所以非常方便易用,但是你必须把它们的值放到内存里,当它们有很多值时就会消耗太多的内存. 62 | 63 | #### Generators 64 | 65 | 生成器也是迭代器的一种,但是你**只能迭代它们一次**.原因很简单,因为它们不是全部存在内存里,它们只在要调用的时候在内存里生成: 66 | 67 | ```python 68 | >>> mygenerator = (x*x for x in range(3)) 69 | >>> for i in mygenerator: 70 | ... print(i) 71 | 0 72 | 1 73 | 4 74 | ``` 75 | 76 | 生成器和迭代器的区别就是用`()`代替`[]`,还有你不能用`for i in mygenerator`第二次调用生成器:首先计算0,然后会在内存里丢掉0去计算1,直到计算完4. 77 | 78 | #### Yield 79 | 80 | `Yield`的用法和关键字`return`差不多,下面的函数将会返回一个生成器: 81 | 82 | ```python 83 | >>> def createGenerator(): 84 | ... mylist = range(3) 85 | ... for i in mylist: 86 | ... yield i*i 87 | ... 88 | >>> mygenerator = createGenerator() # 创建生成器 89 | >>> print(mygenerator) # mygenerator is an object! 90 | 91 | >>> for i in mygenerator: 92 | ... print(i) 93 | 0 94 | 1 95 | 4 96 | ``` 97 | 98 | 在这里这个例子好像没什么用,不过当你的函数要返回一个非常大的集合并且你希望只读一次的话,那么它就非常的方便了. 99 | 100 | 要理解`Yield`你必须先理解当你调用函数的时候,函数里的代码并没有运行.函数仅仅返回生成器对象,这就是它最微妙的地方:-) 101 | 102 | 然后呢,每当`for`语句迭代生成器的时候你的代码才会运转. 103 | 104 | 现在,到了最难的部分: 105 | 106 | 当`for`语句第一次调用函数里返回的生成器对象,函数里的代码就开始运作,直到碰到`yield`,然后会返回本次循环的第一个返回值.所以下一次调用也将运行一次循环然后返回下一个值,直到没有值可以返回. 107 | 108 | 一旦函数运行并且没有碰到`yeild`语句就认为生成器已经为空了.原因有可能是循环结束或者没有满足`if/else`之类的. 109 | 110 | #### 对于你的代码的解释 111 | 112 | 生成器: 113 | 114 | ```python 115 | 116 | # 这里你创建node方法的对象将会返回一个生成器 117 | def node._get_child_candidates(self, distance, min_dist, max_dist): 118 | 119 | # 这里的代码你每次使用生成器对象的时候将会调用 120 | 121 | if self._leftchild and distance - max_dist < self._median: 122 | yield self._leftchild 123 | 124 | if self._rightchild and distance + max_dist >= self._median: 125 | yield self._rightchild 126 | 127 | # 如果代码运行到这里,生成器就被认为变成了空的 128 | ``` 129 | 130 | 调用: 131 | 132 | ```python 133 | # 创建空列表和一个当前对象索引的列表 134 | result, candidates = list(), [self] 135 | 136 | # 在candidates上进行循环(在开始只保含一个元素) 137 | while candidates: 138 | 139 | # 获得最后一个condidate然后从列表里删除 140 | node = candidates.pop() 141 | 142 | # 获取obj和candidate的distance 143 | distance = node._get_dist(obj) 144 | 145 | # 如果distance何时将会填入result 146 | if distance <= max_dist and distance >= min_dist: 147 | result.extend(node._values) 148 | 149 | candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) 150 | 151 | return result 152 | ``` 153 | 154 | 这段代码有几个有意思的地方: 155 | 156 | * 一般的时候我们会在循环迭代一个列表的同时在列表中添加元素:-)尽管在有限循环里结束多少有一些危险,但也不失为一个简单的方法去遍历嵌套的数据.在这里`candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))`将遍历生成器的每一个值,但是`while`循环中的condidates将不再保存已经遍历过的生成器对象,也就是说添加进condidates的生成器对象只会遍历一遍。 157 | 158 | * `extend()`是一个列表对象的方法,它可以把一个迭代对象添加进列表. 159 | 160 | 我们经常这么用: 161 | 162 | ```python 163 | >>> a = [1, 2] 164 | >>> b = [3, 4] 165 | >>> a.extend(b) 166 | >>> print(a) 167 | [1, 2, 3, 4] 168 | ``` 169 | 170 | 但是在你给的代码里得到的是生成器,这样做的好处: 171 | 172 | 1. 你不需要读这个值两次 173 | 2. 你能得到许多孩子节点但是你不希望他们全部存入内存. 174 | 175 | 这种方法之所以能很好的运行是因为Python不关心方法的参数是不是一个列表.它只希望接受一个迭代器,所以不管是strings,lists,tuples或者generators都可以!这种方法叫做duck typing,这也是Python看起来特别cool的原因之一.但是这又是另外一个传说了,另一个问题 176 | 177 | 好了,看到这里可以打住了,下面让我们看看生成器的高级用法: 178 | 179 | #### 控制迭代器的穷尽 180 | 181 | ```python 182 | >>> class Bank(): # 让我们建个银行,生产许多ATM 183 | ... crisis = False 184 | ... def create_atm(self): 185 | ... while not self.crisis: 186 | ... yield "$100" 187 | >>> hsbc = Bank() # 当一切就绪了你想要多少ATM就给你多少 188 | >>> corner_street_atm = hsbc.create_atm() 189 | >>> print(corner_street_atm.next()) 190 | $100 191 | >>> print(corner_street_atm.next()) 192 | $100 193 | >>> print([corner_street_atm.next() for cash in range(5)]) 194 | ['$100', '$100', '$100', '$100', '$100'] 195 | >>> hsbc.crisis = True # cao,经济危机来了没有钱了! 196 | >>> print(corner_street_atm.next()) 197 | 198 | >>> wall_street_atm = hsbc.create_atm() # 对于其他ATM,它还是True 199 | >>> print(wall_street_atm.next()) 200 | 201 | >>> hsbc.crisis = False # 麻烦的是,尽管危机过去了,ATM还是空的 202 | >>> print(corner_street_atm.next()) 203 | 204 | >>> brand_new_atm = hsbc.create_atm() # 只能重新新建一个bank了 205 | >>> for cash in brand_new_atm: 206 | ... print cash 207 | $100 208 | $100 209 | $100 210 | $100 211 | $100 212 | $100 213 | $100 214 | $100 215 | $100 216 | ... 217 | ``` 218 | 219 | 它对于一些不断变化的值很有用,比如说用来控制资源的访问. 220 | 221 | #### Itertools,你的好基友 222 | 223 | itertools模块包含了一些特殊的函数可以操作可迭代对象.有没有想过复制一个生成器?链接两个生成器?把嵌套列表里的值组织成一个列表?Map/Zip还不用创建另一个列表? 224 | 225 | 来吧`import itertools` 226 | 227 | 来一个例子?让我们看看4匹马比赛有多少个排名结果: 228 | 229 | ```python 230 | >>> horses = [1, 2, 3, 4] 231 | >>> races = itertools.permutations(horses) 232 | >>> print(races) 233 | 234 | >>> print(list(itertools.permutations(horses))) 235 | [(1, 2, 3, 4), 236 | (1, 2, 4, 3), 237 | (1, 3, 2, 4), 238 | (1, 3, 4, 2), 239 | (1, 4, 2, 3), 240 | (1, 4, 3, 2), 241 | (2, 1, 3, 4), 242 | (2, 1, 4, 3), 243 | (2, 3, 1, 4), 244 | (2, 3, 4, 1), 245 | (2, 4, 1, 3), 246 | (2, 4, 3, 1), 247 | (3, 1, 2, 4), 248 | (3, 1, 4, 2), 249 | (3, 2, 1, 4), 250 | (3, 2, 4, 1), 251 | (3, 4, 1, 2), 252 | (3, 4, 2, 1), 253 | (4, 1, 2, 3), 254 | (4, 1, 3, 2), 255 | (4, 2, 1, 3), 256 | (4, 2, 3, 1), 257 | (4, 3, 1, 2), 258 | (4, 3, 2, 1)] 259 | ``` 260 | 261 | #### 理解迭代的内部机制 262 | 263 | 迭代是可迭代对象(对应`__iter__()`方法)和迭代器(对应`__next__()`方法)的一个过程.可迭代对象就是任何你可以迭代的对象(废话啊).迭代器就是可以让你迭代可迭代对象的对象(有点绕口,意思就是这个意思) 264 | 265 | 预知后事如何,请看[for 循环是如何工作的](http://effbot.org/zone/python-for-statement.htm) 266 | 267 | 268 | -------------------------------------------------------------------------------- /data/252703.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## Python中的appen和extend 4 | 5 | `append`和`extend`有什么区别? 6 | 7 | *** 8 | 9 | append: 10 | 11 | ```python 12 | x = [1, 2, 3] 13 | x.append([4, 5]) 14 | print (x) 15 | ``` 16 | 17 | 输出:`[1, 2, 3, [4, 5]]` 18 | 19 | extend: 20 | 21 | ```python 22 | x = [1, 2, 3] 23 | x.extend([4, 5]) 24 | print (x) 25 | ``` 26 | 27 | 输出:`[1, 2, 3, 4, 5]` -------------------------------------------------------------------------------- /data/2600191.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何计算列表中元素出现的个数? 4 | 5 | *** 6 | 7 | 如果你想计算单个元素出现的次数,使用 `count` 方法: 8 | 9 | ```python 10 | >>> [1, 2, 3, 4, 1, 4, 1].count(1) 11 | 3 12 | ``` 13 | 14 | **不要**在计算多个元素时使用这个方法.每次调用 `count` 方法都会迭代一边列表,性能会很低,如果你需要计算所有的元素或者指定几个元素可以使用 `Counter`. 15 | 16 | ```python 17 | >>> from collections import Counter 18 | >>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] 19 | >>> Counter(z) 20 | Counter({'blue': 3, 'red': 2, 'yellow': 1}) 21 | ``` 22 | -------------------------------------------------------------------------------- /data/2612802.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何克隆或者 copy 一个 list ? 4 | 5 | 使用 `new_list = my_list` 来 copy list , 但是 每次 `my_list` 改变 `new_list` 都会跟着改变. 6 | 7 | 这是为什么? 8 | 9 | *** 10 | 11 | 用 `new_list = my_list` 来进行 copy 实际上并没有得到两个 list.这个语句并不是真正的复制了一个 list,而是复制了一个 list 的引用, 所以 `my_list` 和 `new_list` 最终指向了同一个 list. 12 | 13 | 为了真正 copy 一个 list, 你可以用下面几种方法: 14 | 15 | * 你可以使用内建函数 `list.copy()` 方法(从 Python3.3 以上可以使用): 16 | ```python 17 | new_list = old_list.copy() 18 | ``` 19 | 20 | * 也可以使用切片: 21 | ```python 22 | new_list = old_list[:] 23 | ``` 24 | [Alex Martelli's](https://en.wikipedia.org/wiki/Alex_Martelli)早在[2007](https://www.youtube.com/watch?v=g7V89K8QfgQ)指出这个切边的语法很奇怪, 他主张用下一个方法可读性更强. 25 | 26 | * 使用内建的 `list()` 函数: 27 | ```python 28 | new_list = list(old_list) 29 | ``` 30 | 31 | * 还可以使用 `copy.copy()`: 32 | ```python 33 | import copy 34 | new_list = copy.copy(old_list) 35 | ``` 36 | 它比 `list()` 方法更慢, 因为它需要先找出 `old_list` 的数据类型. 37 | 38 | * 如果 list 中包含对象并且你也希望 copy 这些对象, 那么可以使用 `copy.deepcopy()`: 39 | ```python 40 | import copy 41 | new_list = copy.deepcopy(old_list) 42 | ``` 43 | 显然这种方法更加慢, 并且需要更多的内存, 但是有些时候不可避免需要用到它. 44 | 45 | 例如: 46 | 47 | ```python 48 | import copy 49 | 50 | class Foo(object): 51 | def __init__(self, val): 52 | self.val = val 53 | 54 | def __repr__(self): 55 | return str(self.val) 56 | 57 | foo = Foo(1) 58 | 59 | a = ['foo', foo] 60 | b = a.copy() 61 | c = a[:] 62 | d = list(a) 63 | e = copy.copy(a) 64 | f = copy.deepcopy(a) 65 | 66 | # edit orignal list and instance 67 | a.append('baz') 68 | foo.val = 5 69 | 70 | print('original: %r\n list.copy(): %r\n slice: %r\n list(): %r\n copy: %r\n deepcopy: %r' 71 | % (a, b, c, d, e, f)) 72 | ``` 73 | 74 | 结果: 75 | 76 | ```python 77 | original: ['foo', 5, 'baz'] 78 | list.copy(): ['foo', 5] 79 | slice: ['foo', 5] 80 | list(): ['foo', 5] 81 | copy: ['foo', 5] 82 | deepcopy: ['foo', 1] 83 | ``` -------------------------------------------------------------------------------- /data/2720014.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 用pip升级所有包 4 | 5 | 可不可以用pip一次性升级所有的Python包? 6 | 7 | 注:在官方的issue里也有这个[需求](http://stackoverflow.com/questions/2720014/upgrading-all-packages-with-pip). 8 | 9 | *** 10 | 11 | 内部还不支持这个命令,但是可以这样: 12 | 13 | ``` 14 | pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs pip install -U 15 | ``` -------------------------------------------------------------------------------- /data/273192.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 检查一个文件夹是否存在,如果不存在就创建它 4 | 5 | 有什么好的方法吗?这个是我想的: 6 | 7 | ```python 8 | filename = "/my/directory/filename.txt" 9 | dir = os.path.dirname(filename) 10 | 11 | try: 12 | os.stat(dir) 13 | except: 14 | os.mkdir(dir) 15 | 16 | f = file(filename) 17 | ``` 18 | 19 | 我忘记了`os.path.exists`(多谢张三,李四,王五的提醒).下面是更改的: 20 | 21 | ```python 22 | def ensure_dir(f): 23 | d = os.path.dirname(f) 24 | if not os.path.exists(d): 25 | os.makedirs(d) 26 | ``` 27 | 28 | 有什么"打开"的标记可以自动的运行? 29 | 30 | *** 31 | 32 | 我看了俩答案都很好,但是都有一点缺陷,所以给出我的: 33 | 34 | 先试`os.path.exists`,然后通过`os.makedirs`来创建. 35 | 36 | ```python 37 | if not os.path.exists(directory): 38 | os.makedirs(directory) 39 | ``` 40 | 41 | 标注一下-如果一个文件在调用`os.path.exists`和`os.makedirs`之间被创建了,将会出现一个`OSError`.遗憾的是捕获`OSError`异常继续进行并不是万无一失的,它将会忽略像磁盘空间不足,没有足够权限等一些其他造成文件创建失败的因素. 42 | 43 | 一个做法是捕获`OSError`异常并检查返回的错误代码(前提是知道错误代码对应的是什么).然而,还有另一种可能,第二次的`os.path.exists`.假如恰好在第一次检查的时候创建了文件夹,然后在第二次检查的时候删掉--我们被耍了~~ 44 | 45 | 根据不同的应用,并行操作的危险或多或少的比其他因素危险.开发者必须在选择开发环境的时候更多地了解特定的应用程序. -------------------------------------------------------------------------------- /data/275018.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何移除换行符? 4 | 5 | 这是我用Python编程遇到的最多的问题了,所以我想放到stackoverflow好让我下次Google'chomp python'的时候能得到有用的答案. 6 | 7 | *** 8 | 9 | 试试`rstrip`方法: 10 | 11 | ```python 12 | >>> 'test string\n'.rstrip() 13 | 'test string' 14 | ``` 15 | 16 | 注意Python的`rstrip`方法将会默认去掉所有的空白符,而在Perl里只是删除换行符.如果只是删除换行符: 17 | 18 | ```python 19 | >>> 'test string \n'.rstrip('\n') 20 | 'test string ' 21 | ``` 22 | 23 | 同样也有`lstrip`和`strip`方法: 24 | 25 | ```python 26 | >>> s = " \n abc def " 27 | >>> s.strip() 28 | 'abc def' 29 | >>> s.rstrip() 30 | ' \n abc def' 31 | >>> s.lstrip() 32 | 'abc def ' 33 | >>> 34 | ``` -------------------------------------------------------------------------------- /data/279237.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何知道一个对象有一个特定的属性? 4 | 5 | 有什么方法可以检测一个对象是否有某些属性?比如: 6 | 7 | ```python 8 | >>> a = SomeClass() 9 | >>> a.someProperty = value 10 | >>> a.property 11 | Traceback (most recent call last): 12 | File "", line 1, in 13 | AttributeError: SomeClass instance has no attribute 'property' 14 | ``` 15 | 16 | 怎样在使用之前知道`a`是否有`property`这个属性? 17 | 18 | *** 19 | 20 | 试试`hasattr()`: 21 | 22 | ```python 23 | if hasattr(a, 'property'): 24 | a.property 25 | ``` 26 | 27 | 在大多数实际情况下,如果一个属性有很大可能存在,那么就直接调用它或者让它引发异常,或者用`try/except`捕获.这种方法比`hasattr`快.如果这个属性很多情况下不在,或者你不确定,那么用`hasattr`将会比触法异常更快. -------------------------------------------------------------------------------- /data/2817869.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## error: Unable to find vcvarsall.bat 4 | 5 | 我试着安装Python的`dulwich`包: 6 | 7 | ```python 8 | pip install dulwich 9 | ``` 10 | 11 | 但是得到了个错误: 12 | 13 | ```python 14 | error: Unable to find vcvarsall.bat 15 | ``` 16 | 17 | 如果手动安装也会出现相同的错误: 18 | 19 | ```python 20 | > python setup.py install 21 | running build_ext 22 | building 'dulwich._objects' extension 23 | error: Unable to find vcvarsall.bat 24 | ``` 25 | 26 | *** 27 | 28 | 对于Windows安装: 29 | 30 | 当安装包运行`setup.py`时,Python2.7会先寻找已经安装的Visual Studio 2008.你可以在运行`setup.py`直线设置正确的`VS90COMNTOOLS`变量. 31 | 32 | 根据Visual Studio的不同执行不同的命令: 33 | 34 | * Visual Studio 2010 (VS10): SET `VS90COMNTOOLS=%VS100COMNTOOLS%` 35 | * Visual Studio 2012 (VS11): SET `VS90COMNTOOLS=%VS110COMNTOOLS%` 36 | * Visual Studio 2013 (VS12): SET `VS90COMNTOOLS=%VS120COMNTOOLS%` -------------------------------------------------------------------------------- /data/2835559.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何解析一个 JSON 文件? 4 | 5 | 我又一个如下的 JSON 文件: 6 | 7 | ```json 8 | { 9 | "maps": [ 10 | { 11 | "id": "blabla", 12 | "iscategorical": "0" 13 | }, 14 | { 15 | "id": "blabla", 16 | "iscategorical": "0" 17 | } 18 | ], 19 | "masks": [ 20 | "id": "valore" 21 | ], 22 | "om_points": "value", 23 | "parameters": [ 24 | "id": "valore" 25 | ] 26 | } 27 | ``` 28 | 29 | 我写了如下代码来打印所有的 json 文本: 30 | 31 | ```python 32 | json_data=open(file_directory).read() 33 | 34 | data = json.loads(json_data) 35 | pprint(data) 36 | ``` 37 | 38 | 如何才能解析文件并且得到单个的值? 39 | 40 | *** 41 | 42 | 额,你的 JSON 文件有错误.在应当用 `{}` 的地方使用了 `[]`. `[]` 是列表, `{}` 是字典. 43 | 44 | 下面是正确的形式: 45 | 46 | ```json 47 | { 48 | "maps": [ 49 | { 50 | "id": "blabla", 51 | "iscategorical": "0" 52 | }, 53 | { 54 | "id": "blabla", 55 | "iscategorical": "0" 56 | } 57 | ], 58 | "masks": { 59 | "id": "valore" 60 | }, 61 | "om_points": "value", 62 | "parameters": { 63 | "id": "valore" 64 | } 65 | } 66 | ``` 67 | 68 | 你可以用如下代码: 69 | 70 | ```python 71 | import json 72 | from pprint import pprint 73 | 74 | with open('data.json') as f: 75 | data = json.load(f) 76 | 77 | pprint(data) 78 | ``` 79 | 80 | 你可以使用 `data` 来得到你想要的值: 81 | 82 | ```python 83 | data["maps"][0]["id"] 84 | data["masks"]["id"] 85 | data["om_points"] 86 | ``` -------------------------------------------------------------------------------- /data/2846653.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何使用线程 4 | 5 | *** 6 | 7 | 这个是2010年提的问题了,这有一种使用 [map](https://docs.python.org/2/library/functions.html#map) 和 [pool](https://docs.python.org/2/library/multiprocessing.html) 的方法来使用线程. 8 | 9 | 下面的代码总结自 [Parallelism in one line: A Better Model for Day to Day Threading Tasks](http://chriskiehl.com/article/parallelism-in-one-line/),仅仅使用了几行代码: 10 | 11 | ```python 12 | from multiprocessing.dummy import Pool as ThreadPool 13 | pool = ThreadPool(4) 14 | results = pool.map(my_function, my_array) 15 | ``` 16 | 17 | 使用 multithreaded 的版本: 18 | 19 | ```python 20 | results = [] 21 | for item in my_array: 22 | results.append(my_function(item)) 23 | ``` 24 | 25 | ### 解释 26 | 27 | > Map 是一个非常 cool 的函数,它可以轻易地使你地 Python 代码实现并行.Map 是从像 Lisp 这种函数式语言学来的.它地作用是对序列中的每个元素进行函数的调用. 28 | > Map 将迭代序列上所有的元素并且调用函数,最后将结果存储到列表中. 29 | 30 | 31 | ![img](../images/2846653-1.png) 32 | 33 | ### 实现 34 | 35 | > 并行版本的 Map 需要两个库来实现: multiprocessing 和 很少人知道地 multiprocessing.dummy. 36 | 37 | `multiprocessing.dummy` 和 multiprocessing 模块很像, [但是使用线程进行替代](https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.dummy)([很重要的区别](https://medium.com/@bfortuner/python-multithreading-vs-multiprocessing-73072ce5600b),进程处理 CPU 密集型作业, 而线程处理 IO 密集型作业): 38 | 39 | > multiprocessing.dummy实现了和 multiprocessing 一样当 API 但是内部使用的是 线程模块 40 | 41 | ```python 42 | import urllib2 43 | from multiprocessing.dummy import Pool as ThreadPool 44 | 45 | urls = [ 46 | 'http://www.python.org', 47 | 'http://www.python.org/about/', 48 | 'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html', 49 | 'http://www.python.org/doc/', 50 | 'http://www.python.org/download/', 51 | 'http://www.python.org/getit/', 52 | 'http://www.python.org/community/', 53 | 'https://wiki.python.org/moin/', 54 | ] 55 | 56 | # make the Pool of workers 57 | pool = ThreadPool(4) 58 | 59 | # open the urls in their own threads 60 | # and return the results 61 | results = pool.map(urllib2.urlopen, urls) 62 | 63 | # close the pool and wait for the work to finish 64 | pool.close() 65 | pool.join() 66 | ``` 67 | 68 | 结果如下: 69 | 70 | ```python 71 | Single thread: 14.4 seconds 72 | 4 Pool: 3.1 seconds 73 | 8 Pool: 1.4 seconds 74 | 13 Pool: 1.3 seconds 75 | ``` 76 | 77 | ### 传入多个参数(像这样[`只在 Python3.3及更高版本生效`](https://stackoverflow.com/a/28975239/2327328)) 78 | 79 | 传入多个数组: 80 | 81 | ```python 82 | results = pool.starmap(function, zip(list_a, list_b)) 83 | ``` 84 | 85 | 或者传递一个 constan 和数组: 86 | 87 | ```python 88 | results = pool.starmap(function, zip(itertools.repeat(constant), list_a)) 89 | ``` 90 | 91 | 如果使用老版本的 Python, 可以通过[这个](https://stackoverflow.com/a/5443941/1893275)方法来实现 92 | -------------------------------------------------------------------------------- /data/287871.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 怎么在终端里输出颜色? 4 | 5 | 怎么样用Python在终端里输出带颜色的文本?最好的代替块字符的unicode字符是什么?(What is the best Unicode symbol to represent a solid block?这句话没理解) 6 | 7 | *** 8 | 9 | 这依赖于你用哪种操作系统.最常用的方法就是输出ANSI转义序列.例如,下面的: 10 | 11 | ```python 12 | class bcolors: 13 | HEADER = '\033[95m' 14 | OKBLUE = '\033[94m' 15 | OKGREEN = '\033[92m' 16 | WARNING = '\033[93m' 17 | FAIL = '\033[91m' 18 | ENDC = '\033[0m' 19 | ``` 20 | 21 | 可以这么用上面的代码: 22 | 23 | ```python 24 | print bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC 25 | ``` 26 | 27 | 这种方法适合OS X,linux和windows系统.还有一些其他的ansi代码可以设置颜色,消除光标或者其他. 28 | 29 | 如果想要应用更复杂的功能(听起来像是如果你正在写一个游戏),你应该看看"curses"模块,它包含了许多关于次部分复杂操作.[Python Curses HowTO](https://docs.python.org/2/howto/curses.html)可以作为好的介绍. 30 | 31 | 如果你不使用拓展的ASCII(比如不是一个PC),`#`或者`@`可能是你最好的选择.如果你用的是[IBM扩展ascii字符设置](http://telecom.tbi.net/asc-ibm.html),你还可以有更多的选择.176,177,178和219是"块字符" 32 | 33 | 一些现代的基于文本的程序,像"Swarf Fortress",显示的文本使用图像模式,而用的字体也是传统的计算机字体的图像.你可以在[Dwarf Fortress Wiki](http://dwarffortresswiki.org/DF2014:Tilesets)找到你可以用的字符. 34 | 35 | [Text Mode Demo Contest ](http://en.wikipedia.org/wiki/Text_Mode_Demo_Contest)也有许多资料可供参考. 36 | 37 | 我想可能有点跑题了.我在设计一个史诗级别的基于文本的冒险游戏.祝你好运! 38 | 39 | *** 40 | 41 | 怎么就没人提[Python termcolor module](https://pypi.python.org/pypi/termcolor).用法相当简单: 42 | 43 | ```python 44 | from termcolor import colored 45 | 46 | print colored('hello', 'red'), colored('world', 'green') 47 | ``` 48 | 49 | 虽然有点简单,但是对于游戏程序和你想要的"colored blocks"来说足够了. -------------------------------------------------------------------------------- /data/30081275.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 为什么 "1000000000000000 in range(1000000000000001)" 在 Python3 里速度那么快? 4 | 5 | 在我理解 `range()` 函数作为 [an object type in Python 3](https://docs.python.org/3/library/stdtypes.html#typesseq-range) 生成的内容和生成器差不多快. 6 | 7 | 我测试如下语句 8 | 9 | ```python 10 | 1000000000000000 in range(1000000000000001) 11 | ``` 12 | 13 | 不管我加了多少个 0 这个计算的结果时间都差不多 14 | 15 | 我还试了下这个, 结果差不多, 非常快: 16 | 17 | ```python 18 | 000000000000000000000 in range(0,1000000000000000000001,10) # count by tens 19 | ``` 20 | 21 | 但是我自己写了个代码速度就非常慢: 22 | 23 | ```python 24 | def my_crappy_range(N): 25 | i = 0 26 | while i < N: 27 | yield i 28 | i += 1 29 | return 30 | ``` 31 | 32 | 所以我想问为啥 `range()` 如此之快? 33 | 34 | *** 35 | 36 | Python3 的 `range()` 对象并不会立即产生数值;它会在需要时来产生.它包含你的起始, 终止和步长, 它会随着每次迭代来产生下一个数值. 37 | 38 | 这个对象通过 [`object.__contains__ hook`](https://docs.python.org/3/reference/datamodel.html#object.__contains__) 来实现的.计算的时间复杂度为 `O(1)`.在迭代的过程中其实是不需要一下计算出所有的数值的. 39 | 40 | 根据 [`range()`](https://docs.python.org/3/library/stdtypes.html#range) 文档 41 | 42 | > `range` 优于于 `list` 和 `tuple` 的地方在于不管它的范围是多少它只占用少量的内存(因为它只保存 `start`, `stop`, `step`, 按需得到数值) 43 | 44 | 所以你可以这么写你的 `range()`: 45 | 46 | ```python 47 | class my_range(object): 48 | def __init__(self, start, stop=None, step=1): 49 | if stop is None: 50 | start, stop = 0, start 51 | self.start, self.stop, self.step = start, stop, step 52 | if step < 0: 53 | lo, hi = stop, start 54 | else: 55 | lo, hi = start, stop 56 | self.length = ((hi - lo - 1) // abs(step)) + 1 57 | 58 | def __iter__(self): 59 | current = self.start 60 | if self.step < 0: 61 | while current > self.stop: 62 | yield current 63 | current += self.step 64 | else: 65 | while current < self.stop: 66 | yield current 67 | current += self.step 68 | 69 | def __len__(self): 70 | return self.length 71 | 72 | def __getitem__(self, i): 73 | if i < 0: 74 | i += self.length 75 | if 0 <= i < self.length: 76 | return self.start + i * self.step 77 | raise IndexError('Index out of range: {}'.format(i)) 78 | 79 | def __contains__(self, num): 80 | if self.step < 0: 81 | if not (self.stop < num <= self.start): 82 | return False 83 | else: 84 | if not (self.start <= num < self.stop): 85 | return False 86 | return (num - self.start) % self.step == 0 87 | ``` 88 | 89 | 这个代码和真正的 `range()` 缺少了像 `.index()`, `.count()` 方法,但是应当可以给你些启发. 90 | 91 | -------------------------------------------------------------------------------- /data/3061.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 通过函数名的字符串来调用这个函数 4 | 5 | 假如我们有个模块叫`foo`,而我有一个`"bar"`字符串.调用`foo.bar()`有什么最好的方法? 6 | 7 | 我需要返回函数值,为什么我不能用`eval`.我想应该能用`eval`来定义一个函数来返回调用的结果,但是我希望更优雅的方法. 8 | 9 | *** 10 | 11 | 假设`foo`有一个`bar`方法: 12 | 13 | ```python 14 | import foo 15 | methodToCall = getattr(foo, 'bar') 16 | result = methodToCall() 17 | ``` 18 | 19 | 第二行和第三行可以简写: 20 | 21 | ```python 22 | result = getattr(foo, 'bar')() 23 | ``` 24 | 25 | 如果让上面的代码更有意义.`getattr`可以用在实例绑定,模块级方法,类方法...等等 -------------------------------------------------------------------------------- /data/306400.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在列表中随机取一个元素 4 | 5 | 例如我有如下列表: 6 | 7 | ```python 8 | foo = ['a', 'b', 'c', 'd', 'e'] 9 | ``` 10 | 11 | 从列表中随机取一个元素最好的方法是什么? 12 | 13 | *** 14 | 15 | ```python 16 | import random 17 | 18 | foo = ['a', 'b', 'c', 'd', 'e'] 19 | print(random.choice(foo)) 20 | ``` -------------------------------------------------------------------------------- /data/312443.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在Python怎么样才能把列表分割成同样大小的块? 4 | 5 | 我有一个任意长度的列表,我需要把它们切成相同大小并且使用它们.有一些简单的方法,比如设置一个计数器和两个列表,当第二个列表装满后,把它存进第一个列表然后让第二个列表变空一遍存放下一轮的数据,但是这么做代价太大了. 6 | 7 | 我想是不是还有其他更好的方法,比如生成器 8 | 9 | 像下面这样: 10 | 11 | ```python 12 | l = range(1, 1000) 13 | print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] 14 | ``` 15 | 16 | 我试着在`itertools`找一些有用的方法,但是还没有找到.也可能是我还没有看到. 17 | 18 | 相似问题:[What is the most “pythonic” way to iterate over a list in chunks?]() 19 | 20 | *** 21 | 22 | 下面是生成器方法: 23 | 24 | ```python 25 | def chunks(l, n): 26 | """ Yield successive n-sized chunks from l. 27 | """ 28 | for i in xrange(0, len(l), n): 29 | yield l[i:i+n] 30 | ``` 31 | 32 | ```python 33 | import pprint 34 | pprint.pprint(list(chunks(range(10, 75), 10))) 35 | [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], 36 | [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], 37 | [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], 38 | [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], 39 | [50, 51, 52, 53, 54, 55, 56, 57, 58, 59], 40 | [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], 41 | [70, 71, 72, 73, 74]] 42 | ``` 43 | 44 | *** 45 | 46 | 一句话 47 | 48 | ```python 49 | tuple(l[i:i+n] for i in xrange(0, len(l), n)) 50 | ``` -------------------------------------------------------------------------------- /data/3207219.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在Python中列出目录中的所有文件 4 | 5 | 怎么样用Python列出一个目录的所有文件并且存进一个列表? 6 | 7 | *** 8 | 9 | [`os.listdir()`](http://docs.python.org/library/os.html#os.listdir)可以获得一个目录中所有文件或者子目录. 10 | 11 | 如果你只想要文件的话,你也可以用`os.path`把其他的过滤掉: 12 | 13 | ```python 14 | from os import listdir 15 | from os.path import isfile, join 16 | onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ] 17 | ``` 18 | 或者你可以用[`os.walk()`](http://docs.python.org/library/os.html#os.walk),它遍历每个目录将会返回两个列表(一个文件列表,一个目录列表),如果你想要顶层目录只需要在第一次迭代后break一下即可. 19 | 20 | ```python 21 | from os import walk 22 | 23 | f = [] 24 | for (dirpath, dirnames, filenames) in walk(mypath): 25 | f.extend(filenames) 26 | break 27 | ``` 28 | 29 | 最后,如果你想增加列表可以像上面那样用`.extend()`或者: 30 | 31 | ```python 32 | >>> q = [1,2,3] 33 | >>> w = [4,5,6] 34 | >>> q = q + w 35 | >>> q 36 | [1,2,3,4,5,6] 37 | ``` 38 | 39 | 我个人更喜欢`.extend()`# 在Python中列出目录中的所有文件 40 | 41 | -------------------------------------------------------------------------------- /data/3220404.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 为什么用pip比用easy_install的好? 4 | 5 | 一个推特写道: 6 | 7 | 别用easy_install,除非你想自讨苦吃.那么用pip. 8 | 9 | 为什么要用`pip`而不是`easy_install`?如果一个作者上传一个损坏的源文件包(比如丢失文件,没有setup.py),那么`pip`和`easy_install`都将失效.除了这些,为什么Python使用者(像上面那个)**强烈**建议用`pip`而不是`easy_install`? 10 | 11 | *** 12 | 13 | 来自Lan Bicking的自己对于[`pip`](https://pip.pypa.io/en/1.5.X/other-tools.html#easy-install)的介绍: 14 | 15 | 16 | pip是对easy_install以下方面进行了改进: 17 | 18 | * 所有的包是在安装之前就下载了.所以不可能出现只安装了一部分. 19 | * 在终端上的输出更加友好. 20 | * 对于动作的原因进行持续的跟踪.例如,如果一个包正在安装,那么pip就会跟踪为什么这个包会被安装. 21 | * 错误信息会非常有用. 22 | * 代码简洁精悍可以很好的编程. 23 | * 不必作为egg存档,能扁平化安装(仍然保存egg元数据) 24 | * 原生的支持其他版本控制系统(Git, Mercurial and Bazaar) 25 | * 卸载包 26 | * 可以简单的定义修改一系列的安装依赖,还可以可靠的赋值一系列包. 27 | 28 | -------------------------------------------------------------------------------- /data/3277503.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 把文件一行行读入数组 4 | 5 | 怎么样才能一行行的读一个文件并把每行作为一个元素存入一个数组? 6 | 7 | 我想读取文件的没一行,然后把每行加入到数组的最后.我没找到这样的方法而且我也没能在Python中找到创建字符数组的方法. 8 | 9 | *** 10 | 11 | ```python 12 | with open(fname) as f: 13 | content = f.readlines() 14 | ``` 15 | 16 | 我想你说的是[list](http://docs.python.org/glossary.html#term-list)而不是数组. -------------------------------------------------------------------------------- /data/3294889.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 使用 for 来迭代字典的原理 4 | 5 | 有点不理解下面的代码: 6 | 7 | ```python 8 | d = {'x': 1, 'y': 2, 'z': 3} 9 | for key in d: 10 | print key, 'corresponds to', d[key] 11 | ``` 12 | 13 | 我有点不理解 `key` 的部分. Python 是怎么识别出只需要从字典中读取 key? `key` 是 Python 里的关键词还是只是一个简单的变量? 14 | 15 | *** 16 | 17 | `key` 就是一个变量名. 18 | 19 | ```python 20 | for key in d: 21 | ``` 22 | 23 | 上面的语句紧紧会循环字典中的 key ,而不是 key 和 value.如果需要循环 key 和 value, 你可以用下面的方法: 24 | 25 | Python 2.x: 26 | 27 | ```python 28 | for key, value in d.iteritems(): 29 | ``` 30 | 31 | Python 3.x: 32 | 33 | ```python 34 | for key, value in d.items(): 35 | ``` 36 | 37 | 你可以自己试一下用其他变量替换 `key`. 38 | 39 | 在 Python3 里 `iteritems()` 简化成了 `items()`, 它能像 `iteritems()`一样返回一个基于字典本身的像 set 一样的 view, 但是做了更多的优化.在 Python 2.7 里和 `viewitems()` 的效果是一样的. 40 | 41 | 在 Python2 和 Python3 里都有 `items()`, 但是在 2 中只会返回一个 list, 它的结构是这种 `(key, value)` 键值对的形式, 它不能反映出在字典调用 `items()` 后做出的改变.所以在 Python3.x 中需要使用 `list(d.items())` 才能与之等价. -------------------------------------------------------------------------------- /data/332289.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何改变 matplotlib 图像大小 4 | 5 | *** 6 | 7 | [figure](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.figure.html#matplotlib.pyplot.figure)告诉你如何操作: 8 | 9 | ```python 10 | from matplotlib.pyplot import figure 11 | figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k') 12 | ``` 13 | 14 | `figure(figsize=(1,1))` 可以创建一个 1x1 英寸的图像, 由 80x80 像素组成,如果想改变像素,可以改变 dpi 大小. -------------------------------------------------------------------------------- /data/339007.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 给字符串填充0 4 | 5 | 有什么方法可以给字符串左边填充0,这样就可以有一个特定长度. 6 | 7 | *** 8 | 9 | 字符串: 10 | 11 | ```python 12 | >>> n = '4' 13 | >>> print n.zfill(3) 14 | >>> '004' 15 | ``` 16 | 17 | 对于数字: 18 | 19 | ```python 20 | >>> n = 4 21 | >>> print '%03d' % n 22 | >>> 004 23 | >>> print format(4, '03') # python >= 2.6 24 | >>> 004 25 | >>> print "{0:03d}".format(4) # python >= 2.6 26 | >>> 004 27 | >>> print("{0:03d}".format(4)) # python 3 28 | >>> 004 29 | ``` 30 | 31 | *** 32 | 33 | ```python 34 | >>> t = 'test' 35 | >>> t.rjust(10, '0') 36 | >>> '000000test' 37 | ``` 38 | -------------------------------------------------------------------------------- /data/3394835.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## `*args`和 `**kwargs` 4 | 5 | 我对`*args`和`**kwargs`的概念有点不理解. 6 | 7 | 到目前位置我了解到: 8 | 9 | * `*args` = 参数列表-作为可选参数 10 | * `**kwargs` = 字典-参数的关键字作为键,它们的值作为字典的值. 11 | 12 | ?? 13 | 14 | 说实话我不裂解这对编程来说有什么用?(我知道它,但是对他不了解.) 15 | 16 | 或许: 17 | 18 | 我想把字典或者列表当做参数的同时也把它们当成通配符,所以可以传递任何参数? 19 | 20 | 有什么实际例子来解释怎么用`*args`和`**kwargs`? 21 | 22 | 通过教程我只是用了"*"和一个变量名. 23 | 24 | 还是`*args`和`**kwargs`只是一个占位符,你们在代码里用`*args`和`**kwargs`吗? 25 | 26 | *** 27 | 28 | [`*`和`**`的语法](http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists).用`*args`和`**kwargs`只是为了方便并没有强制使用它们. 29 | 30 | 当你不确定你的函数里将要传递多少参数时你可以用`*args`.例如,它可以传递任意数量的参数: 31 | 32 | ```python 33 | >>> def print_everything(*args): 34 | for count, thing in enumerate(args): 35 | ... print '{0}. {1}'.format(count, thing) 36 | ... 37 | >>> print_everything('apple', 'banana', 'cabbage') 38 | 0. apple 39 | 1. banana 40 | 2. cabbage 41 | ``` 42 | 43 | 相似的,`**kwargs`允许你使用没有事先定义的参数名: 44 | 45 | ```python 46 | >>> def table_things(**kwargs): 47 | ... for name, value in kwargs.items(): 48 | ... print '{0} = {1}'.format(name, value) 49 | ... 50 | >>> table_things(apple = 'fruit', cabbage = 'vegetable') 51 | cabbage = vegetable 52 | apple = fruit 53 | ``` 54 | 55 | 你也可以混着用.命名参数首先获得参数值然后所有的其他参数都传递给`*args`和`**kwargs`.命名参数在列表的最前端.例如: 56 | 57 | ```python 58 | def table_things(titlestring, **kwargs) 59 | ``` 60 | 61 | `*args`和`**kwargs`可以同时在函数的定义中,但是`*args`必须在`**kwargs`前面. 62 | 63 | 当调用函数时你也可以用`*`和`**`语法.例如: 64 | 65 | ```python 66 | >>> def print_three_things(a, b, c): 67 | ... print 'a = {0}, b = {1}, c = {2}'.format(a,b,c) 68 | ... 69 | >>> mylist = ['aardvark', 'baboon', 'cat'] 70 | >>> print_three_things(*mylist) 71 | a = aardvark, b = baboon, c = cat 72 | ``` 73 | 74 | 就像你看到的一样,它可以传递列表(或者元组)的每一项并把它们解包.注意必须与它们在函数里的参数相吻合.当然,你也可以在函数定义或者函数调用时用`*`. -------------------------------------------------------------------------------- /data/3437059.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## Python中有检查字符串包含的方法吗? 4 | 5 | 我正在找`string.contains`或者`string.indexof`方法. 6 | 7 | 我希望: 8 | 9 | ```python 10 | if not somestring.contains("blah"): 11 | continue 12 | ``` 13 | 14 | *** 15 | 16 | 你可以用`in`啊: 17 | 18 | ```python 19 | if not "blah" in somestring: continue 20 | ``` 21 | 22 | 或者: 23 | 24 | ```python 25 | if "blah" not in somestring: continue 26 | ``` -------------------------------------------------------------------------------- /data/354038.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 检查一个字符串是否是一个数字 4 | 5 | 如果一个字符串可以被看做一个数字那么有什么好的方法可以检测出来? 6 | 7 | 我能想到的方法: 8 | 9 | ```python 10 | def is_number(s): 11 | try: 12 | float(s) 13 | return True 14 | except ValueError: 15 | return False 16 | ``` 17 | 18 | 我还没有想到什么更好的方法. 19 | 20 | *** 21 | 22 | 对字符串对象用`isdigit()`方法: 23 | 24 | ```python 25 | >>> a = "03523" 26 | >>> a.isdigit() 27 | True 28 | ``` 29 | 30 | ```python 31 | >>> b = "963spam" 32 | >>> b.isdigit() 33 | False 34 | ``` 35 | 36 | [String Methods - isdigit()](http://docs.python.org/library/stdtypes.html#str.isdigit) 37 | 38 | 同样也有unicode的方法,但是我不太熟悉[Unicode - Is decimal/decimal](http://docs.python.org/library/stdtypes.html#unicode.isnumeric) 39 | -------------------------------------------------------------------------------- /data/36901.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## Python中`**`和`*`参数有什么用? 4 | 5 | 见55 -------------------------------------------------------------------------------- /data/36932.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在Python里如何用枚举类型? 4 | 5 | 我是一个C#开发者,但是我现在做的工作是关于Python的. 6 | 7 | 怎么在Python里代替枚举类型呢? 8 | 9 | *** 10 | 11 | PEP435标准里已经把枚举添加到Python3.4版本,在Pypi中也可以向后支持3.3, 3.2, 3.1, 2.7, 2.6, 2.5, 和 2.4版本. 12 | 13 | 如果想向后兼容`$ pip install enum34`,如果下载`enum`(没有数字)将会是另一个版本. 14 | 15 | ```python 16 | from enum import Enum 17 | Animal = Enum('Animal', 'ant bee cat dog') 18 | ``` 19 | 20 | 或者等价于: 21 | 22 | ```python 23 | class Animals(Enum): 24 | ant = 1 25 | bee = 2 26 | cat = 3 27 | dog = 4 28 | ``` 29 | 30 | 在更早的版本,下面这种方法来完成枚举: 31 | 32 | ```python 33 | def enum(**enums): 34 | return type('Enum', (), enums) 35 | ``` 36 | 37 | 像这样来用: 38 | 39 | ```python 40 | >>> Numbers = enum(ONE=1, TWO=2, THREE='three') 41 | >>> Numbers.ONE 42 | 1 43 | >>> Numbers.TWO 44 | 2 45 | >>> Numbers.THREE 46 | 'three' 47 | ``` 48 | 49 | 也很容易支持自动计数,像下面这样: 50 | 51 | ```python 52 | def enum(*sequential, **named): 53 | enums = dict(zip(sequential, range(len(sequential))), **named) 54 | return type('Enum', (), enums) 55 | ``` 56 | 57 | 这样用: 58 | 59 | ```python 60 | >>> Numbers = enum('ZERO', 'ONE', 'TWO') 61 | >>> Numbers.ZERO 62 | 0 63 | >>> Numbers.ONE 64 | 1 65 | ``` 66 | 67 | 如果要把值转换为名字可以加入下面的方法: 68 | 69 | ```python 70 | def enum(*sequential, **named): 71 | enums = dict(zip(sequential, range(len(sequential))), **named) 72 | reverse = dict((value, key) for key, value in enums.iteritems()) 73 | enums['reverse_mapping'] = reverse 74 | return type('Enum', (), enums) 75 | ``` 76 | 77 | 这样会覆盖名字下的所有东西,但是对于枚举的输出很有用.如果转换的值不存在就会抛出`KeyError`异常.用前面的例子: 78 | 79 | ```python 80 | >>> Numbers.reverse_mapping['three'] 81 | 'THREE' 82 | ``` 83 | -------------------------------------------------------------------------------- /data/372885.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何连接MySQL? 4 | 5 | 在python程序里如何链接MySQL数据库? 6 | 7 | *** 8 | 9 | ### 连接MYSQL需要3步 10 | 11 | #### 1 安装 12 | 13 | 你必须先安装MySQL驱动.和PHP不一样,Python只默认安装了SQLite的驱动.最常用的包是[MySQLdb](http://pypi.python.org/pypi/MySQL-python/)但是用`easy_install`安装很困难. 14 | 15 | 对于Window用户,你可以获取[MySQLdb](http://sourceforge.net/project/showfiles.php?group_id=22307)的exe. 16 | 17 | 对于Linux,可以下载`python-mysqldb`(可以用`sudo apt-get install python-mysqldb`命令直接在命令行下载) 18 | 19 | 对于Mac用户,可以用Macport下载[MySQLdb](http://stackoverflow.com/questions/1448429/how-to-install-mysqldb-python-data-access-library-to-mysql-on-mac-os-x#1448476) 20 | 21 | #### 2 使用 22 | 23 | 装完之后重启.这不是强制的,但是这样做可以减少问题.所以请重启. 24 | 25 | 然后就像用其他包一样: 26 | 27 | ```python 28 | #!/usr/bin/python 29 | import MySQLdb 30 | 31 | db = MySQLdb.connect(host="localhost", # your host, usually localhost 32 | user="john", # your username 33 | passwd="megajonhy", # your password 34 | db="jonhydb") # name of the data base 35 | 36 | # you must create a Cursor object. It will let 37 | # you execute all the queries you need 38 | cur = db.cursor() 39 | 40 | # Use all the SQL you like 41 | cur.execute("SELECT * FROM YOUR_TABLE_NAME") 42 | 43 | # print all the first cell of all the rows 44 | for row in cur.fetchall() : 45 | print row[0] 46 | ``` 47 | 48 | 当然,还有许多用法和选项,我只是举了一个基本的例子.你可以看看文档.[A good starting point.](http://www.mikusa.com/python-mysql-docs/) 49 | 50 | #### 3 高级用法 51 | 52 | 一旦你知道它是如何工作的,你可能想用[ORM](https://en.wikipedia.org/wiki/Object-Relational_Mapping)来避免手动写入SQL,来把表变成Python对象.Python中最有名的ORM叫做[SQLAlchemy](http://www.sqlalchemy.org/) 53 | 54 | 我强烈推荐:你的生活质量肯定能获得提高. 55 | 56 | 最近在Python里又发现了一个好东西:[peewee](http://peewee.readthedocs.org/en/latest/index.html).它是个非常轻巧的ORM,非常容易安装和使用.我的小项目和独立app都使用它,而那些工具像SQLLAlchemy或者Django用在这里有点小题大做了: 57 | 58 | ```python 59 | import peewee 60 | from peewee import * 61 | 62 | db = MySQLDatabase('jonhydb', user='john',passwd='megajonhy') 63 | 64 | class Book(peewee.Model): 65 | author = peewee.CharField() 66 | title = peewee.TextField() 67 | 68 | class Meta: 69 | database = db 70 | 71 | Book.create_table() 72 | book = Book(author="me", title='Peewee is cool') 73 | book.save() 74 | for book in Book.filter(author="me"): 75 | print book.title 76 | 77 | Peewee is cool 78 | ``` 79 | 80 | 这个例子可以运行.除了peewee(`pip install peewee`)不需要别的的依赖.安装不复杂.它非常cool! -------------------------------------------------------------------------------- /data/379906.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 把字符串解析成浮点数或者整数 4 | 5 | 在Python里,怎么样把一个数字型字符串像`"545.2222"`解析成对应的浮点值`545.2222`?或者把一个`"31"`解析成`31`? 6 | 7 | 我只是想知道怎么样才能解析一个浮点型字符串编程浮点数,或者整型字符串转换成整型? 8 | 9 | *** 10 | 11 | ```python 12 | >>> a = "545.2222" 13 | >>> float(a) 14 | 545.22220000000004 15 | >>> int(float(a)) 16 | 545 17 | ``` -------------------------------------------------------------------------------- /data/38987.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何在一个表达式里合并两个字典? 4 | 5 | 我有两个Python字典,我想写一个表达式来返回两个字典的合并.update()方法返回的是空值而不是返回合并后的对象. 6 | 7 | ```python 8 | >>> x = {'a':1, 'b': 2} 9 | >>> y = {'b':10, 'c': 11} 10 | >>> z = x.update(y) 11 | >>> print z 12 | None 13 | >>> x 14 | {'a': 1, 'b': 10, 'c': 11} 15 | ``` 16 | 17 | 怎么样才能最终让值保存在z而不是x? 18 | 19 | *** 20 | 21 | 可以用下面的方法: 22 | 23 | ``` 24 | z = dict(x.items() + y.items()) 25 | ``` 26 | 27 | 最后就是你想要的最终结果保存在字典z中,而键`b`的值会被第二个字典的值覆盖. 28 | 29 | ```python 30 | >>> x = {'a':1, 'b': 2} 31 | >>> y = {'b':10, 'c': 11} 32 | >>> z = dict(x.items() + y.items()) 33 | >>> z 34 | {'a': 1, 'c': 11, 'b': 10} 35 | ``` 36 | 37 | 如果你用的是Python3的话稍微有点麻烦: 38 | 39 | ```python 40 | >>> z = dict(list(x.items()) + list(y.items())) 41 | >>> z 42 | {'a': 1, 'c': 11, 'b': 10} 43 | ``` 44 | 45 | *** 46 | 47 | 还可以这样: 48 | 49 | ```python 50 | z = x.copy() 51 | z.update(y) 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /data/394809.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在Python中有三元运算符吗? 4 | 5 | 如果没有,可以像其他语言用的简单方法来实现吗? 6 | 7 | *** 8 | 9 | 有,在2.5版本中加入.对于python初学者可能有点难以理解,所以要记住了. 10 | 11 | 语法如下: 12 | 13 | ```python 14 | a if test else b 15 | ``` 16 | 17 | 根据`test`的布尔值来判断返回的是`a`还是`b`;如果`test`为真则返回`a`,反之则返回`b`. 18 | 19 | 来个大栗子: 20 | 21 | ```python 22 | >>> 'true' if True else 'false' 23 | 'true' 24 | >>> 'true' if False else 'false' 25 | 'false' 26 | ``` 27 | 28 | 官方文档: 29 | * [Conditional expressions](https://docs.python.org/3/reference/expressions.html#conditional-expressions) 30 | * [Is there an equivalent of C’s ”?:” ternary operator?](https://docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator) 31 | 32 | 33 | -------------------------------------------------------------------------------- /data/3964681.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 找出文件夹中所有扩展名位 .txt 的文件 4 | 5 | *** 6 | 7 | 可以使用 [`glob`](https://docs.python.org/2/library/glob.html): 8 | 9 | ```python 10 | import glob, os 11 | os.chdir("/mydir") 12 | for file in glob.glob("*.txt"): 13 | print(file) 14 | ``` 15 | 16 | 或者 [`os.listdir`](https://docs.python.org/2/library/os.html#os.listdir) 17 | 18 | ```python 19 | import os 20 | for file in os.listdir("/mydir"): 21 | if file.endswith(".txt"): 22 | print(os.path.join("/mydir", file)) 23 | ``` 24 | 25 | 或者你想迭代所有的目录, 可以使用 [`os.walk`](https://docs.python.org/2/library/os.html#os.walk) 26 | 27 | ```python 28 | import os 29 | for root, dirs, files in os.walk("/mydir"): 30 | for file in files: 31 | if file.endswith(".txt"): 32 | print(os.path.join(root, file)) 33 | 34 | ``` -------------------------------------------------------------------------------- /data/402504.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何查看 Python 变量的类型? 4 | 5 | *** 6 | 7 | Python 不像 C/C++,不会出现你的问题 8 | 9 | 试一下: 10 | 11 | ```python 12 | >>> i = 123 13 | >>> type(i) 14 | 15 | >>> type(i) is int 16 | True 17 | >>> i = 123456789L 18 | >>> type(i) 19 | 20 | >>> type(i) is long 21 | True 22 | >>> i = 123.456 23 | >>> type(i) 24 | 25 | >>> type(i) is float 26 | True 27 | ``` 28 | 29 | 在 Python3.0中 int 和 long 已经不再进行区分了. -------------------------------------------------------------------------------- /data/415511.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在Python里获取当前时间 4 | 5 | 用什么方法或者模块获取当前时间? 6 | 7 | *** 8 | 9 | ```python 10 | >>> import datetime 11 | >>> datetime.datetime.now() 12 | datetime(2009, 1, 6, 15, 8, 24, 78915) 13 | ``` 14 | 15 | 如果只要时间: 16 | 17 | ```python 18 | >>> datetime.datetime.time(datetime.datetime.now()) 19 | datetime.time(15, 8, 24, 78915) 20 | ``` 21 | 22 | 同样功能但是更紧凑的写法: 23 | 24 | ```python 25 | >>> datetime.datetime.now().time() 26 | ``` 27 | 28 | 获取更多信息,看[文档](http://docs.python.org/library/datetime.html). 29 | 30 | 如果还要节省输出,可以在从`datetime`模块import`datetime`对象: 31 | 32 | ```python 33 | >>> from datetime import datetime 34 | ``` 35 | 36 | 然后把所有`datetime.`从头部去掉. -------------------------------------------------------------------------------- /data/419163.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## `if __name__ == "__main__":`有什么作用? 4 | 5 | ```python 6 | # Threading example 7 | import time, thread 8 | 9 | def myfunction(string, sleeptime, lock, *args): 10 | while True: 11 | lock.acquire() 12 | time.sleep(sleeptime) 13 | lock.release() 14 | time.sleep(sleeptime) 15 | 16 | if __name__ == "__main__": 17 | lock = thread.allocate_lock() 18 | thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) 19 | thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) 20 | ``` 21 | 22 | *** 23 | 24 | 当 Python 解析器读取一个源文件时, 会执行里面所有的代码. 25 | 26 | 但是在它执行之前会定义一些特殊的变量.例如,如果 Python 解析器把一个 module(the source file)当成主程序来执行的话, 它会把 `__name__` 的值设置成为 `__main__`.如果这个文件是被其他 module 引入的, `__name__`的名字将会被设成 module 的名字. 27 | 28 | 在你给的例子中, 我们假设作为一个主程序来执行, 例如在 shell 里执行如下命令 29 | 30 | ```shell 31 | python threading_example.py 32 | ``` 33 | 34 | 当设置好特殊变量后, 它会执行 `import` 声明并且开始载入这些 modules.它会执行 `def` 代码块, 创建一个函数对象并且会创建一个 `myfunction` 的变量指向这个函数对象.接下来它会读取 `if` 语句并且判断 `__name__` 是否等于 `__main__`, 如果等于就执行代码块里面的程序. 35 | 36 | 你想创建一个 module (一个 `.py` 文件), 同时也想能够被其他 module 引用.填入 `if __name__ == "__main__":` 能使你在以这个 module 作为主程序时才会执行, 而其他外部引用不会执行这些代码. 37 | 38 | 可以在 [这里](http://ibiblio.org/g2swap/byteofpython/read/module-name.html) 查看更多细节 -------------------------------------------------------------------------------- /data/423379.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何在一个函数里用全局变量? 4 | 5 | 如果我在一个函数里建了一个全局变量,那么我怎么在另一个函数里使用这个全局变量? 6 | 7 | 我需要把这个全局变量赋值给这个函数的局部变量吗? 8 | 9 | *** 10 | 11 | 如果你要在别的函数里使用全局变量,只要在被调用全局变量函数的里事先用`global`声明一下: 12 | 13 | ```python 14 | globvar = 0 15 | 16 | def set_globvar_to_one(): 17 | global globvar # 需要用global修饰一下globvar 18 | globvar = 1 19 | 20 | def print_globvar(): 21 | print globvar # 如果要读globbar的值的话不需要用global修饰 22 | 23 | set_globvar_to_one() 24 | print_globvar() # 输出 1 25 | ``` 26 | 27 | 我猜正是因为全局变量比较危险,所以Python为了确保你真的知道它是全局变量,所以需要加一个`global`关键字. 28 | 29 | -------------------------------------------------------------------------------- /data/448271.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## `__init__.py` 的作用 4 | 5 | *** 6 | 7 | 它是作为包的一部分. [文档](http://docs.python.org/tutorial/modules.html#packages) 8 | 9 | > `__init__.py` 作为标识 Python 包的文件, 这么做是为了防止 Python 在引入 module 时误引入其他类似 `string` 这样的通用名.`__init__.py` 最简单的方式是空文件, 但是它可以为包执行初始化代码或者设置 `__all__` 变量 10 | -------------------------------------------------------------------------------- /data/455612.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 限制浮点型到小数点后两位 4 | 5 | 我希望 `a` 可以转化成 13.95 6 | 7 | ```python 8 | >>> a 9 | 13.949999999999999 10 | >>> round(a, 2) 11 | 13.949999999999999 12 | ``` 13 | 14 | [round](https://docs.python.org/2/library/functions.html#round) 并没有像我期待的那样得到 13.95 15 | 16 | *** 17 | 18 | 你遇到了典型的浮点数问题,那就是浮点数并不能代表所有的数值.命令行展示的只是内存中的完整的浮点数的形式. 19 | 20 | 上面的浮点数和你想要的结果是等价的.因为计算机是二进制的,它将浮点数存为整形,并且除以2的幂,所以 13.95 将会表示成 125650429603636838/(2**53). 21 | 22 | 双精度数值有53个字节来表示精度,而浮点型有24个字节表示.Python 使用 [双精度浮点数](http://docs.python.org/tutorial/floatingpoint.html) 来存储数值. 23 | 24 | 例如, 25 | 26 | ```python 27 | >>> 125650429603636838/(2**53) 28 | 13.949999999999999 29 | 30 | >>> 234042163/(2**24) 31 | 13.949999988079071 32 | 33 | >>> a=13.946 34 | >>> print(a) 35 | 13.946 36 | >>> print("%.2f" % a) 37 | 13.95 38 | >>> round(a,2) 39 | 13.949999999999999 40 | >>> print("%.2f" % round(a,2)) 41 | 13.95 42 | >>> print("{0:.2f}".format(a)) 43 | 13.952 44 | >>> print("{0:.2f}".format(round(a,2))) 45 | 13.95 46 | >>> print("{0:.15f}".format(round(a,2))) 47 | 13.949999999999999 48 | ``` 49 | 50 | 如果你想要精确到小数点后2位有两个不错的选择: 51 | 52 | 1. 使用整数并以美分存储值,而不是美元,然后除以100转换为美元。(没看懂,可能是 Python 的货币计算?) 53 | 2. 使用 Python 的 [decimal](http://docs.python.org/library/decimal.html) -------------------------------------------------------------------------------- /data/466345.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 把字符串转化成时间 4 | 5 | 短小精悍.我有一个特别大的列表存储了下面的字符串: 6 | 7 | ```python 8 | Jun 1 2005 1:33PM 9 | Aug 28 1999 12:00AM 10 | ``` 11 | 12 | 我想把它们转化成合适的时间格式存进数据库,所以我需要把它们变成真正的时间对象. 13 | 14 | 非常感谢帮助. 15 | 16 | *** 17 | 18 | 检查[time](http://docs.python.org/2/library/time.html)模块的[strptime](http://docs.python.org/2/library/time.html#time.strptime)函数.它是[strftime](http://docs.python.org/2/library/time.html#time.strftime)的转换. 19 | 20 | *** 21 | 22 | ```python 23 | from datetime import datetime 24 | 25 | date_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p') 26 | ``` -------------------------------------------------------------------------------- /data/4706499.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何增加文件的内容? 4 | 5 | 如何做到 append 文件而不是覆盖? 6 | 7 | *** 8 | 9 | ```python 10 | with open("test.txt", "a") as myfile: 11 | myfile.write("appended text") 12 | ``` -------------------------------------------------------------------------------- /data/4750806.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 怎么在windows下安装pip? 4 | 5 | 怎么在windows下安装pip? 6 | 7 | *** 8 | 9 | ### Python3.4+ 10 | 11 | 好消息,Python3.4已经自带Pip.这是所有Python发行版中最好的特性了.方便了所有人使用公共库.新手再也不用操心安装额外库的繁琐步骤了.它自带的包管理器中加入了 Ruby, Nodejs, Haskell, Perl, Go等其他几乎所有的开源社区流行语言.谢谢Python. 12 | 13 | 当然,这并不意味着所有的Python包问题已经解决.在一段时间看来仍然不乐观.我在[Python有包管理系统吗?](http://stackoverflow.com/questions/2436731/does-python-have-a-package-module-management-system/13445719#13445719)也讨论过这个问题. 14 | 15 | 同样对于Python2.x用户(几乎一般人),还没有计划在Python中自带Pip. 16 | 只能自己动手了. 17 | 18 | ### Python 2.x 和 Python ≤ 3.3 19 | 20 | 尽管Python吹的`简单易用`的哲学,但是Python不提供包管理工具.更糟糕的是,Pip直到现在还是非常的难以安装. 21 | 22 | #### 官方指南 23 | 24 | 在 http://www.pip-installer.org/en/latest/installing.html 下载`get-pip.py`,把它保存下来注意不要把`.py`后缀改成`.txt`. 25 | 然后在命令提示符上输入: 26 | 27 | ``` 28 | python get-pip.py 29 | ``` 30 | 31 | 你可能还需要管理员权限来执行它.跟着做 http://technet.microsoft.com/en-us/library/cc947813(v=ws.10).aspx 32 | 33 | #### 另一种方法 34 | 35 | 官方文档告诉我们安装Pip和各种依赖的源.对有经验的人来说太麻烦了,对于新手又有点难. 36 | 37 | Christoph Gohlke已经为我们做好了下载Python包的安装器(.msi).它可以为的Python版本建立依赖,不管32bit还是64bit.你只需要: 38 | 39 | * 安装setuptools http://www.lfd.uci.edu/~gohlke/pythonlibs/#setuptools 40 | * 安装pip http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip 41 | 42 | 在我这,Pip安装到了`C:\Python27\Scripts\pip.exe`.在你的电脑上找到`pip.exe`,然后把文件夹(eg.`C:\Python27\Scripts`)添加你的路径(编辑你的环境变量).现在你应当可以在命令行中运行pip了.试试安装一个包: 43 | 44 | ``` 45 | pip install httpie 46 | ``` 47 | 48 | 终于可以运行了!下面是一些问题的解决办法 49 | 50 | #### 代理问题 51 | 52 | 如果你在办公环境,那么你有可能有一个HTTP代理.把环境变量设置成[`http_proxy`和`https_proxy`](https://docs.python.org/2/library/urllib.html).大多数应用程序都管用(包括免费软件).语法如下: 53 | 54 | ``` 55 | http://proxy_url:port 56 | http://username:password@proxy_url:port 57 | ``` 58 | 59 | 如果你不幸用的是微软的NTLM代理.那就没救了.唯一的办法就是安装一个友好的代理吧. http://cntlm.sourceforge.net/ 60 | 61 | #### 找不到vcvarsall.bat 62 | 63 | Python有的模块是用C或C++写的.Pip尝试从源码编译.如果你没有安装或设置过C/C++编译器,你将会看到下面的错误: 64 | 65 | ``` 66 | Error: Unable to find vcvarsall.bat 67 | ``` 68 | 69 | 你可以通过像MinGw或者Visual C++这样的[C++编译器](http://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat)来解决此问题.微软实际上已经自带了一个为Python准备的编译器,或者试试 http://aka.ms/vcpython27 70 | 71 | 可以这个Christoph的网站来查看安装包 http://www.lfd.uci.edu/~gohlke/pythonlibs/ 72 | -------------------------------------------------------------------------------- /data/4906977.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在 Python 中如何获取环境变量 4 | 5 | *** 6 | 7 | 环境变量可以通过 [`os.environ`](https://docs.python.org/library/os.html#os.environ) 来获取 8 | 9 | ```python 10 | import os 11 | print(os.environ['HOME']) 12 | ``` 13 | 14 | 或者你可以查看一下所有环境变量的列表: 15 | 16 | ```python 17 | os.environ 18 | ``` 19 | 20 | ```python 21 | # using get will return `None` if a key is not present rather than raise a `KeyError` 22 | print(os.environ.get('KEY_THAT_MI¡GHT_EXIST')) 23 | 24 | # os.getenv is equivalent, and can also give a default value instead of `None` 25 | print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value)) 26 | ``` 27 | 28 | [`Python default installation`](https://docs.python.org/install/index.html#how-installation-works) 在 Windows 中是 `C:\Python`, 如果你想在运行时得到可以运行下面的: 29 | 30 | ```python 31 | import sys 32 | print(sys.prefix) 33 | ``` -------------------------------------------------------------------------------- /data/493386.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何使打印的内容没有空格或换行 4 | 5 | 在 `c` 语言中我可以这么打印: 6 | 7 | ```c 8 | #include 9 | 10 | int main() { 11 | int i; 12 | for (i=0; i<10; i++) printf("."); 13 | return 0; 14 | } 15 | ``` 16 | 17 | 输出: 18 | 19 | ``` 20 | .......... 21 | ``` 22 | 23 | 在 Python 里: 24 | 25 | ```python 26 | >>> for i in xrange(0,10): print '.' 27 | . 28 | . 29 | . 30 | . 31 | . 32 | . 33 | . 34 | . 35 | . 36 | . 37 | >>> for i in xrange(0,10): print '.', 38 | . . . . . . . . . . 39 | ``` 40 | 41 | 在 Python 里 `print` 会加上 `\n` 或者空格, 如何避免? 42 | 43 | *** 44 | 45 | ### 通用做法 46 | 47 | ```python 48 | import sys 49 | sys.stdout.write('.') 50 | ``` 51 | 52 | 你也可以调用 53 | 54 | ```python 55 | sys.stdout.flush() 56 | ``` 57 | 58 | 来确保 `stdout` 立即刷新 59 | 60 | ### Python 2.6+ 61 | 62 | 在 Python2.6 里你可以引入 Python3 的 `print` 函数: 63 | 64 | ```python 65 | from __future__ import print_function 66 | ``` 67 | 68 | 这样可以用 Python3 来解决上面的问题 69 | 70 | ### Python3 71 | 72 | 在 Python3 中, `print` 语句变成了函数.在 Python3 中你可以: 73 | 74 | ```python 75 | print('.', end='') 76 | ``` 77 | 78 | 在 Python2 中也可以, 确保你引入 `from __future__ import print_function`. 79 | 80 | 如果你在缓冲遇到了麻烦, 你可以在后面加上 `flush=True` 参数: 81 | 82 | ```python 83 | print('.', end='', flush=True) 84 | ``` 85 | 86 | 注意 `flush` 关键字在 Python2 里引入 `__future__` 后并不生效;它只在 Python3 里, 更精确的说是 3.3 或以上.在老版本里你需要手动调用 `sys.stdout.flush()`. -------------------------------------------------------------------------------- /data/493819.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 为什么是string.join(list)而不是list.join(string)? 4 | 5 | 我一直被这个问题困扰.如果这样写更好: 6 | 7 | ```python 8 | my_list = ["Hello", "world"] 9 | print my_list.join("-") 10 | # Produce: "Hello-world" 11 | ``` 12 | 13 | 而不是: 14 | 15 | ```python 16 | my_list = ["Hello", "world"] 17 | print "-".join(my_list) 18 | # Produce: "Hello-world" 19 | ``` 20 | 21 | 有什么特殊的原因让它不这样做吗? 22 | 23 | *** 24 | 25 | 是因为所有的可迭代对象都能被`join`,不仅仅是列表,但结果是我们一般要`join`的都是字符串. 26 | 27 | 例如: 28 | 29 | ```python 30 | import urllib2 31 | print '\n############\n'.join(urllib2.urlopen('http://data.stackexchange.com/users/7095')) 32 | ``` -------------------------------------------------------------------------------- /data/5082452.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 字符串格式化:%和.format 4 | 5 | Python2.6推出了[str.format()]方法,和原有的%格式化方式有小小的区别.那个方法更好? 6 | 7 | 1. 下面的方法有同样的输出,它们的区别是什么? 8 | 9 | ``` 10 | #!/usr/bin/python 11 | sub1 = "python string!" 12 | sub2 = "an arg" 13 | 14 | a = "i am a %s" % sub1 15 | b = "i am a {0}".format(sub1) 16 | 17 | c = "with %(kwarg)s!" % {'kwarg':sub2} 18 | d = "with {kwarg}!".format(kwarg=sub2) 19 | 20 | print a # "i am a python string!" 21 | print b # "i am a python string!" 22 | print c # "with an arg!" 23 | print d # "with an arg!" 24 | ``` 25 | 2. 另外在Python中格式化字符串什么时候执行?例如如果我的loggin的优先级设置为高,那么我还能用`%`操作符吗?如果是这样的话,有什么方法可以避免吗? 26 | 27 | log.debug("some debug info: %s" % some_info) 28 | 29 | *** 30 | 31 | 先回答第一个问题...`.format`在许多方面看起来更便利.你可以重用参数,但是你用`%`就不行.最烦人的是`%`它无法同时传递一个变量和元组.你可能会想下面的代码不会有什么问题: 32 | 33 | "hi there %s" % name 34 | 35 | 但是,如果`name`恰好是`(1,2,3)`,它将会抛出一个`TypeError`异常.为了保证它总是正确的,你必须这样做: 36 | 37 | "hi there %s" % (name,) # 提供一个单元素的数组而不是一个参数 38 | 39 | 但是有点丑.`.format`就没有这些问题.你给的第二个问题也是这样,`.format`好看多了. 40 | 41 | 你为什么不用它? 42 | 43 | * 不知道它(在读这个之前) 44 | * 为了和Python2.5兼容 45 | 46 | 回答你的第二个问题,字符串格式和其他操作一样发生在它们运行的时候.Python是非懒惰语言,在函数调用前执行表达式,所以在你的`log.debug`例子中,`"some debug info: %s"%some_info`将会先执行,先生成`"some debug info: roflcopters are active"`,然后字符串将会传递给`log.debug()` -------------------------------------------------------------------------------- /data/509211.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 理解Python切片 4 | 5 | 对于Python的切片有什么好的资料吗?对我来说理解切片有点难度.它看起来非常有用,但是我还是不能理解它,我正在找有什么好的资料. 6 | 7 | *** 8 | 9 | 非常简单: 10 | 11 | ```python 12 | a[start:end] # 从start开始到end-1结束 13 | a[start:] # 从start开始直到末尾 14 | a[:end] # 从头部开始直到end结束 15 | a[:] # 复制整个列表 16 | ``` 17 | 18 | 这里还有一个`step`值,可以用在上面素有例子的后面: 19 | 20 | ```python 21 | a[start:end:step] # 按照step步长直到end-1结束,并不是从start一个个遍历到end 22 | ``` 23 | 24 | 重点需要记住的是:`:end`值代表的是不被选中的第一个位置.所以`end`和`start`区别在于选中的元素(如果`step`默认为1) 25 | 26 | 另一点要说的是`start`或者`end`可能是个负数,也就是从尾部而不是从头部开始计数.所以: 27 | 28 | ```python 29 | a[-1] # 列表最后一个元素 30 | a[-2:] # 列表最后两个元素 31 | a[:-2] # 除了最后两个元素剩下的部分 32 | ``` 33 | 如果你调用的元素多于列表中含有的元素个数,Python也会很友好的表示.例如,如果你请求`a[:-2]`而`a`只含有一个元素,你得到的是一个空列表而不是一个错误信息.有些时候你可能更希望得到这个错误信息,所以你得意识到上面的事可能发生. 34 | 35 | 36 | -------------------------------------------------------------------------------- /data/510348.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在 Python 里如何手工进行延迟? 4 | 5 | *** 6 | 7 | ```python 8 | import time 9 | time.sleep(5) # Delays for 5 seconds. You can also use a float value. 10 | ``` 11 | 12 | 这里有另一个例子展示每隔差不多一分钟运行一次: 13 | 14 | ```python 15 | import time 16 | while True: 17 | print("This prints once a minute.") 18 | time.sleep(60) # Delay for 1 minute (60 seconds). 19 | ``` -------------------------------------------------------------------------------- /data/510972.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何获取实例的类名 4 | 5 | 如何才能获取一个实例对象的类名? 6 | 7 | 我想或许[the inspect module](https://docs.python.org/library/inspect)可以实现,但是好像还没有发现什么能帮我的.或许可以分析`__class__`成员,但是我不知道怎么用. 8 | 9 | *** 10 | 11 | 你试没试类里的`__name__`属性?比如`x.__class__.__name__`或许可以得到你想要的 12 | 13 | ```python 14 | >>> import itertools 15 | >>> x = itertools.count(0) 16 | >>> x.__class__.__name__ 17 | 'count' 18 | ``` 19 | 20 | 注:如果你用的是新式类(从Python2.2),你可以调用`type()`函数来替代: 21 | 22 | ```python 23 | >>> type(x).__name__ 24 | 'count' 25 | ``` 26 | 27 | 像`int`这种内建方法也可以: 28 | 29 | ```python 30 | >>> (5).__class__.__name__ 31 | 'int' 32 | >>> type(5).__name__ 33 | 'int' 34 | ``` -------------------------------------------------------------------------------- /data/5137497.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 查找当前目录和文件目录 4 | 5 | 在 Python 中什么命令可以找到: 6 | 7 | 1. 当前目录(在终端中运行的 Python 脚本) 8 | 2. 我执行的文件在哪里? 9 | 10 | *** 11 | 12 | 可以通过下面的命令获得执行的 Python 文件所在的位置: 13 | 14 | ```python 15 | import os 16 | dir_path = os.path.dirname(os.path.realpath(__file__)) 17 | ``` 18 | 19 | (注意当你已经使用 `os.chdir()` 来该改变当前工作目录的话, 上面得到的结果并不准确, 因为 `__file__` 变量只表示当前工作目录的相对位置, 不会被 `os.chdir()` 所改变) 20 | 21 | 获取当前工作目录: 22 | 23 | ```python 24 | import os 25 | cwd = os.getcwd() 26 | ``` 27 | 28 | 下面是几个函数,模块或者变量的文档: 29 | 30 | * [`os`](https://docs.python.org/library/os.html) 和 [`os.path`](https://docs.python.org/library/os.path.html#module-os.path) 模块. 31 | * [`__file__`](https://docs.python.org/reference/datamodel.html) 变量 32 | * [`os.path.realpath(path)`](https://docs.python.org/library/os.path.html#os.path.realpath) 33 | * [`os.path.dirname(path)`](https://docs.python.org/library/os.path.html#os.path.dirname) 34 | * [`os.getcwd()`](https://docs.python.org/library/os.html#os.getcwd) 35 | * [`os.chdir(path)`](https://docs.python.org/library/os.html#os.chdir) -------------------------------------------------------------------------------- /data/522563.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在循环中获取索引(数组下标) 4 | 5 | 有人知道如何获取列表的索引值吗: 6 | 7 | ```python 8 | ints = [8, 23, 45, 12, 78] 9 | ``` 10 | 11 | 当我循环这个列表时如何获得它的索引下标? 12 | 13 | *** 14 | 15 | 如果像C或者PHP那样加入一个状态变量那就太不pythonic了. 16 | 17 | 最好的选择就是用内建函数[enumerate](https://docs.python.org/2/library/functions.html#enumerate) 18 | 19 | ```python 20 | for idx, val in enumerate(ints): 21 | print idx, val 22 | ``` 23 | 24 | 想了解更多可以查看[PEP279].在Python2.x和Python3.x都好使. -------------------------------------------------------------------------------- /data/53513.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 检查列表是否为空的最好方法 4 | 5 | 例如,传递下面: 6 | 7 | ``` 8 | a = [] 9 | ``` 10 | 11 | 我怎么检查`a`是空值? 12 | 13 | *** 14 | 15 | ```python 16 | if not a: 17 | print "List is empty" 18 | ``` 19 | 20 | 用隐藏的空列表的布尔值才是最Pythonic的方法. -------------------------------------------------------------------------------- /data/5466451.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何在 .format 中使用大括号? 4 | 5 | ```python 6 | x = " \{ Hello \} {0} " 7 | print x.format(42) 8 | ``` 9 | 10 | 得到了: `Key Error: Hello\\` 11 | 12 | 我希望输出: `{Hello} 42` 13 | 14 | *** 15 | 16 | 你需要写两次, `{{` 和 `}}`: 17 | 18 | ```python 19 | >>> x = " {{ Hello }} {0} " 20 | >>> print x.format(42) 21 | ' { Hello } 42 ' 22 | ``` 23 | 24 | 文档在这里 [Python documentation for format string syntax](http://docs.python.org/library/string.html#formatstrings)" 25 | 26 | 格式化中的大括号 `{}` 表示替代字段.任何不再大括号中的将被看做文本,会被原样输出.如果你在文本中包含大括号, 你可以使用 `{{` 和 `}}`. 27 | -------------------------------------------------------------------------------- /data/5574702.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 输出到stderr 4 | 5 | 我知道至少三种方法这么做: 6 | 7 | ```python 8 | import sys 9 | sys.stderr.write('spam\n') 10 | 11 | print >> sys.stderr, 'spam' 12 | 13 | from __future__ import print_function 14 | print('spam', file=sys.stderr) 15 | ``` 16 | 17 | 但是看起来和python的第13条宗旨相违背,所以有什么更好的方法吗?或者上面那些方法有什么可以改进? 18 | 19 | >There should be one — and preferably only one — obvious way to do it. 20 | 21 | *** 22 | 23 | 我发现只有这个方法短小+便捷+可读性好: 24 | 25 | ```python 26 | from __future__ import print_function 27 | def warning(*objs): 28 | print("WARNING: ", *objs, file=sys.stderr) 29 | ``` 30 | 31 | *** 32 | 33 | 我会选择`sys.stderr.write()`,更可读而且言简意赅的突出重点,最主要的是在所有版本都可以用. 34 | 35 | 注:`Pythonic`是除了可读和效率意外才考虑的事情...如果记住前两条的话80%的代码就已经是`Pythonic`了.列表推导式是一个'big thing'所以不经常用(可读性). -------------------------------------------------------------------------------- /data/576169.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 理解Python中`super()`和`__init__()`方法 4 | 5 | 我试着理解`super()`方法.从表面上看,两个子类实现的功能都一样.我想问它们俩的区别在哪里? 6 | 7 | ```python 8 | class Base(object): 9 | def __init__(self): 10 | print "Base created" 11 | 12 | class ChildA(Base): 13 | def __init__(self): 14 | Base.__init__(self) 15 | 16 | class ChildB(Base): 17 | def __init__(self): 18 | super(ChildB, self).__init__() 19 | 20 | print ChildA(),ChildB() 21 | ``` 22 | 23 | *** 24 | 25 | 26 | `super()`的好处就是可以避免直接使用父类的名字.但是它主要用于多重继承,[这里面](http://www.artima.com/weblogs/viewpost.jsp?thread=236275)有很多好玩的东西.如果还不了解的话可以看看[官方文档](https://docs.python.org/2/library/functions.html#super) 27 | 28 | 注意在Python3.0里语法有所改变:你可以用`super().__init__()`替换`super(ChildB, self).__init__()`.(在我看来非常nice) -------------------------------------------------------------------------------- /data/582336.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何测量脚本运行时间? 4 | 5 | 我在Project Euler发现好多这样的问题,许多其他地方也问怎么测量执行时间.但是有的时候答案有点kludgey-比如,在`__main__`中加入时间代码,所以我想在这里分享一下解决方案. 6 | 7 | *** 8 | 9 | Python自带了一个叫`cProfile`的分析器.它不仅实现了计算整个时间,而且单独计算每个函数运行时间,并且告诉你这个函数被调用多少次,它可以很容易的确定你要优化的值. 10 | 11 | 你可以在你的代码里或是交互程序里调用,像下面这样: 12 | 13 | ```python 14 | import cProfile 15 | cProfile.run('foo()') 16 | ``` 17 | 18 | 更有用的是,你可以在运行脚本的时候用`cProfile`: 19 | 20 | ``` 21 | python -m cProfile myscript.py 22 | ``` 23 | 24 | 为了使用更简单,我做了一个小脚本名字叫`profile.bat`: 25 | 26 | ``` 27 | python -m cProfile %1 28 | ``` 29 | 30 | 所以我可以这么调用了: 31 | 32 | ``` 33 | profile euler048.py 34 | ``` 35 | 36 | 下面是结果: 37 | 38 | ```python 39 | 1007 function calls in 0.061 CPU seconds 40 | 41 | Ordered by: standard name 42 | ncalls tottime percall cumtime percall filename:lineno(function) 43 | 1 0.000 0.000 0.061 0.061 :1() 44 | 1000 0.051 0.000 0.051 0.000 euler048.py:2() 45 | 1 0.005 0.005 0.061 0.061 euler048.py:2() 46 | 1 0.000 0.000 0.061 0.061 {execfile} 47 | 1 0.002 0.002 0.053 0.053 {map} 48 | 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler objects} 49 | 1 0.000 0.000 0.000 0.000 {range} 50 | 1 0.003 0.003 0.003 0.003 {sum} 51 | ``` 52 | 53 | 注:更新一个来自PyCon2013的视频网址: http://lanyrd.com/2013/pycon/scdywg/ -------------------------------------------------------------------------------- /data/60208.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## Python中用什么代替switch语句? 4 | 5 | 我想写一个函数,实现输入一个值对应输出另一个值. 6 | 7 | 在其他语言我可以用`switch`或者`case`语句,但是Python里没有`switch`.Python里如何解决这个问题? 8 | 9 | *** 10 | 11 | 你可以用一个字典: 12 | 13 | ```python 14 | def f(x): 15 | return { 16 | 'a': 1, 17 | 'b': 2, 18 | }[x] 19 | ``` 20 | 21 | *** 22 | 23 | 如果你希望设置一个默认值可以用字典的`get`方法: 24 | 25 | ```python 26 | def f(x): 27 | return { 28 | 'a': 1, 29 | 'b': 2, 30 | }.get(x, 9) # 9 is default if x not found 31 | ``` -------------------------------------------------------------------------------- /data/606191.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## bytes 换成 string 4 | 5 | 我通过这个代码来获取外部程序的输出: 6 | 7 | ```python 8 | >>> from subprocess import * 9 | >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] 10 | ``` 11 | 12 | communicate() 方法返回一个字节数组: 13 | 14 | ```python 15 | >>> command_stdout 16 | b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' 17 | ``` 18 | 19 | 但是我想让它输出成 Python string. 像这样: 20 | 21 | ```python 22 | >>> print(command_stdout) 23 | -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 24 | -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 25 | ``` 26 | 27 | 我试着用 [`binascii.b2a_qp()`](http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp) 方法但是如下: 28 | 29 | ```python 30 | >>> binascii.b2a_qp(command_stdout) 31 | b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' 32 | ``` 33 | 34 | 谁知道怎么讲字节转换成 string ? 35 | 36 | *** 37 | 38 | 你需要 decode 字节对象来产生 string: 39 | 40 | ```python 41 | >>> b"abcde" 42 | b'abcde' 43 | 44 | # utf-8 is used here because it is a very common encoding, but you 45 | # need to use the encoding your data is actually in. 46 | >>> b"abcde".decode("utf-8") 47 | 'abcde' 48 | ``` -------------------------------------------------------------------------------- /data/610883.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在 Python 中如何得到对象的所有属性? 4 | 5 | 有没有什么方法可以检测对象是否有一个属性?例如: 6 | 7 | ```python 8 | >>> a = SomeClass() 9 | >>> a.someProperty = value 10 | >>> a.property 11 | Traceback (most recent call last): 12 | File "", line 1, in 13 | AttributeError: SomeClass instance has no attribute 'property' 14 | ``` 15 | 16 | 怎么样才能在用 `porperty` 之前知道 `a` 有这个属性? 17 | 18 | *** 19 | 20 | 试试 [hasattr()](https://docs.python.org/3/library/functions.html#hasattr): 21 | 22 | ```python 23 | if hasattr(a, 'property'): 24 | a.property 25 | ``` 26 | 27 | 答案2 28 | 29 | `hasattr` 可以做到,但是我要说一句 Python 鼓励 "easier to ask for forgiveness than permission" (EAFP) 而不是 "look before you leap" (LBYL).详细查看下面链接: 30 | 31 | [EAFP vs LBYL (was Re: A little disappointed so far)](http://web.archive.org/web/20070929122422/http://mail.python.org/pipermail/python-list/2003-May/205182.html) 32 | [EAFP vs. LBYL @Code Like a Pythonista: Idiomatic Python](https://web.archive.org/web/20180411011411/http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#eafp-vs-lbyl) 33 | 34 | 例如: 35 | 36 | ```python 37 | try: 38 | doStuff(a.property) 39 | except AttributeError: 40 | otherStuff() 41 | ``` 42 | 43 | 要比下面的更好 44 | 45 | ```python 46 | if hasattr(a, 'property'): 47 | doStuff(a.property) 48 | else: 49 | otherStuff() 50 | ``` 51 | 52 | -------------------------------------------------------------------------------- /data/613183.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 用字典的值(key)对字典进行排序 4 | 5 | 我有个字典,字典的值来自于数据库:一个是字符串,一个是数字.字符串是唯一的,所以键(key)就是字符串. 6 | 7 | 我可以用键(key)来排序,但是怎么用值(value)来排序呢? 8 | 9 | 注:我已经看过另一个问题[怎样对列表中的字典的键值(key)对字典进行排序?](http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary-in-python),或许这种方法可以,但是我确实只需要一个字典,我想看看还有其他更好的方法. 10 | 11 | *** 12 | 13 | 对字典进行排序是不可能的,只有把字典转换成另一种方式才能排序.字典本身是无序的,但是像列表元组等其他类型是有序的.所以你需要用一个元组列表来表示排序的字典. 14 | 15 | 例子: 16 | 17 | ```python 18 | import operator 19 | x = {1: 2, 3: 4, 4:3, 2:1, 0:0} 20 | sorted_x = sorted(x.items(), key=operator.itemgetter(1)) 21 | ``` 22 | 23 | `sorted_x`是一个元组列表,用每个元组的第二个元素进行排序.`dict(sorted_x) == x`. 24 | 25 | 如果想要用键(key)来进行排序: 26 | 27 | ``` 28 | import operator 29 | x = {1: 2, 3: 4, 4:3, 2:1, 0:0} 30 | sorted_x = sorted(x.items(), key=operator.itemgetter(0)) 31 | ``` 32 | 33 | *** 34 | 35 | 你也可以: 36 | 37 | ``` 38 | sorted(d.items(), key=lambda x: x[1]) 39 | ``` 40 | 41 | -------------------------------------------------------------------------------- /data/627435.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何删除 list 中指定 index 的元素? 4 | 5 | *** 6 | 7 | 使用 `del` 并且指定你想删除的元素的 index: 8 | 9 | ```python 10 | >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 11 | >>> del a[-1] 12 | >>> a 13 | [0, 1, 2, 3, 4, 5, 6, 7, 8] 14 | ``` 15 | 16 | 同时支持切片: 17 | 18 | ```python 19 | >>> del a[2:4] 20 | >>> a 21 | [0, 1, 4, 5, 6, 7, 8, 9] 22 | ``` -------------------------------------------------------------------------------- /data/6470428.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在一行里获取多个异常 4 | 5 | 我知道这样: 6 | 7 | ```python 8 | try: 9 | # 可能错的地方 10 | except: 11 | # 如果错了执行这里 12 | ``` 13 | 14 | 也知道这样: 15 | 16 | ```python 17 | try: 18 | # 可能错的地方 19 | except IDontLikeYourFaceException: 20 | # 给爷笑一个 21 | except YouAreTooShortException: 22 | # 踩高跷 23 | ``` 24 | 25 | 但是我想在两个不同的异常里做同样的事,我能想到的办法: 26 | 27 | ```python 28 | try: 29 | # 可能错的地方 30 | except IDontLIkeYouException: 31 | # 滚 32 | except YouAreBeingMeanException: 33 | # 滚 34 | ``` 35 | 36 | 有什么方法能像下面那样: 37 | 38 | ```python 39 | try: 40 | # 可能错的地方 41 | except IDontLIkeYouException, YouAreBeingMeanException: 42 | # 滚 43 | ``` 44 | 45 | 现在下面的代码根本不好使: 46 | 47 | ```python 48 | try: 49 | # 可能错的地方 50 | except Exception, e: 51 | # 滚 52 | ``` 53 | 54 | 所以有什么方法可以完成我的要求吗? 55 | 56 | *** 57 | 58 | 用括号扩起来: 59 | 60 | ```python 61 | except (IDontLIkeYouException, YouAreBeingMeanException) as e: 62 | pass 63 | ``` 64 | 65 | 用逗号分割的方法只能在Python2.6和2.7里好使,在Python3中则无效;现在,你应当使用`as`. 66 | -------------------------------------------------------------------------------- /data/663171.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 获得一个字符串的子串 4 | 5 | 有什么方法获得一个字符串的字串,比如从一个字符串的第三个字符到最后. 6 | 7 | 可能是`myString[2:end]`? 8 | 9 | *** 10 | 11 | ```python 12 | >>> x = "Hello World!" 13 | >>> x[2:] 14 | 'llo World!' 15 | >>> x[:2] 16 | 'He' 17 | >>> x[:-2] 18 | 'Hello Worl' 19 | >>> x[-2:] 20 | 'd!' 21 | >>> x[2:-2] 22 | 'llo Worl' 23 | ``` 24 | 25 | 上面的概念在Python中叫"slicing"(切片),不止在字符串上有这个方法.在[这里](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation)有详细的解释. -------------------------------------------------------------------------------- /data/6797984.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在 Python 中如何将字符串转回为小写 4 | 5 | *** 6 | 7 | ```Python 8 | s = "Kilometer" 9 | print(s.lower()) 10 | ``` 11 | 12 | 官方文档 [`str.lower`](https://docs.python.org/3.4/library/stdtypes.html?highlight=str.lower#str.lower) -------------------------------------------------------------------------------- /data/68645.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## Python 中类的静态变量 4 | 5 | 在 Python 中如何实现类的静态变量或者方法 6 | 7 | *** 8 | 9 | 在类定义中声明且在方法里未声明的是类的静态变量 10 | 11 | ```python 12 | >>> class MyClass: 13 | ... i = 3 14 | ... 15 | >>> MyClass.i 16 | 3 17 | ``` 18 | 19 | 这样做会生成一个类级别的 `i` 变量, 而不是依赖于某个实例的 `i` 变量, 所以你可以: 20 | 21 | ```python 22 | >>> m = MyClass() 23 | >>> m.i = 4 24 | >>> MyClass.i, m.i 25 | >>> (3, 4) 26 | ``` 27 | 28 | 和 C++ 和 Java 不一样, 这种静态变量不能通过实例来访问有点像 C#. 29 | 30 | 可以看一看 [what the Python tutorial has to say on the subject of classes and class objects](https://docs.python.org/2/tutorial/classes.html#class-objects) 31 | 32 | [static methods](http://web.archive.org/web/20090214211613/http://pyref.infogami.com/staticmethod) 的相关文档 ["Built-in Functions" in the Python Library Reference](https://docs.python.org/2/library/functions.html#staticmethod) 33 | 34 | ```python 35 | class C: 36 | @staticmethod 37 | def f(arg1, arg2, ...): ... 38 | ``` 39 | 40 | 有人提到使用 [classmethod](https://docs.python.org/2/library/functions.html#classmethod) 作为静态方法, 它接受类的类型作为第一个参数, 但是我依然对这种方法的有点疑问, 如果你也是, 那可能没什么关系 -------------------------------------------------------------------------------- /data/6996603.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 删除文件或者文件夹 4 | 5 | *** 6 | 7 | [`os.remove()`](http://docs.python.org/library/os.html#os.remove) 删除文件 8 | [`os.rmdir()`](http://docs.python.org/library/os.html#os.rmdir) 删除空文件夹 9 | [`shutil.rmtree()`](http://docs.python.org/library/shutil.html#shutil.rmtree) 删除文件夹和里面的内容 10 | [`pathlib.Path.unlink()`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.unlink) 删除文件或链接 11 | [`pathlib.Path.rmdir()`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.unlink) 删除空文件夹 12 | -------------------------------------------------------------------------------- /data/72899.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 通过列表中字典的值对列表进行排序 4 | 5 | 我的到了一个字典的列表,我想对字典的值进行排序. 6 | 7 | ```python 8 | [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] 9 | ``` 10 | 11 | 对name进行排序,应当是: 12 | 13 | ```python 14 | [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}] 15 | ``` 16 | 17 | *** 18 | 19 | 用key比用cmp更清晰明了: 20 | 21 | ```python 22 | newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) 23 | ``` 24 | 25 | 或者其他人的建议: 26 | 27 | ```python 28 | from operator import itemgetter 29 | newlist = sorted(list_to_be_sorted, key=itemgetter('name')) 30 | ``` 31 | -------------------------------------------------------------------------------- /data/735975.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 静态方法 4 | 5 | Python有没有静态方法使我可以不用实例化一个类就可以调用,像这样: 6 | 7 | ```python 8 | ClassName.StaticMethod ( ) 9 | ``` 10 | 11 | *** 12 | 13 | 是的,用[静态方法](https://docs.python.org/2/library/functions.html#staticmethod)装饰器 14 | 15 | ```python 16 | class MyClass(object): 17 | @staticmethod 18 | def the_static_method(x): 19 | print x 20 | 21 | MyClass.the_static_method(2) # outputs 2 22 | ``` 23 | 24 | 注意有些代码用一个函数而不是`staticmethod`装饰器去定义一个静态方法.如果你想支持Python的老版本(2.2和2.3)可以用下面的方法: 25 | 26 | ```python 27 | class MyClass(object): 28 | def the_static_method(x): 29 | print x 30 | the_static_method = staticmethod(the_static_method) 31 | 32 | MyClass.the_static_method(2) # outputs 2 33 | ``` 34 | 35 | 这个方法和第一个一样,只是没有第一个用装饰器的优雅. 36 | 37 | 最后,请少用`staticmethod`方法!在Python里只有很少的场合适用静态方法,其实许多顶层函数会比静态方法更清晰明了. 38 | 39 | [文档](https://docs.python.org/2/library/functions.html#staticmethod) -------------------------------------------------------------------------------- /data/82831.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 用Python如何一个文件是否存在? 4 | 5 | 不用`try:`语句可以一个文件存在 6 | 7 | *** 8 | 9 | 如果不确定文件存不存在,可以这样做: 10 | 11 | ```python 12 | import os.path 13 | os.path.isfile(fname) 14 | ``` 15 | 16 | -------------------------------------------------------------------------------- /data/89228.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在Python中调用外部命令? 4 | 5 | 怎么在Python脚本里调用外部命令?(就好像直接输入在Unix shell中或者windows的命令行里) 6 | 7 | *** 8 | 9 | 来来来,我给你叨咕叨咕各种方法和各自优缺点: 10 | 11 | 1. `os.system("命令加参数")`把命令和参数传递给你系统的shell中.用这个命令的好处在于你可以一次运行好多命令还可以设置管道来进行重定向.来个栗子:`os.system("命令 < 出入文件 | 另一个命令 > 输出文件")`尽管它非常方便,但是你还是不得不手动输入像空格这样的sehll字符.从另一方面讲,对于运行简单的shell命令而不去调用外部程序来说的话还是非常好用的. 12 | 2. `stream = os.popen("命令和参数")`这个命令和`os.system`差不多,但是它提供了一个连接标准输入/输出的管道.还有其他3个`popen`可以调用.如果你传递一个字符串,你的命令会把它传递给shell,如果你传递的是一个列表,那么就不用担心溢出字符了(escaping characters). 13 | 3. `subprocess`模块的管道`Popen`.这个`Popen`是打算用来替代`os.popen`的方法,它有点复杂: 14 | 15 | ```python 16 | print subprocess.Popen("echo Hello World", shell=True,stdout=PIPE).stdout.read() 17 | ``` 18 | 19 | 而用`os.popen`: 20 | 21 | ```python 22 | print os.popen("echo Hello World").read() 23 | ``` 24 | 25 | 它最大的优点就是一个类里代替了原来的4个不同的`popen` 26 | 27 | 4. `subprocess`的`call`方法.它的基本用法和上面的`Popen`类参数一致,但是它会等待命令结束后才会返回程序.来个大狸子: 28 | 29 | ```python 30 | return_code = subprocess.call("echo Hello World", shell=True) 31 | ``` 32 | 33 | 5. os模块里也有C语言里`fork/exec/spawn`方法,但是我不建议你直接用它们. 34 | 35 | 36 | `subprocess`模块可能更适合你. 37 | 38 | 最后请注意在你传递到shell的命令一定要注意参数的安全性,给你个提示,看下面代码 39 | 40 | ```python 41 | print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read() 42 | ``` 43 | 44 | 想象一下如果哪个 SB 输入 `my mama didnt love me && rm -rf /` 45 | 46 | -------------------------------------------------------------------------------- /data/930397.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 获取列表最后一个元素 4 | 5 | 在Python里,如何获取一个列表的最后一个元素? 6 | 7 | *** 8 | 9 | `some_list[-1]`最短最Pythonic的方法. 10 | 11 | 事实上你可以用这个语法做好多事.`some_list[-n]`语法获取倒数第n个元素.所以`some_list[-1]`获取最后一个元素,`some_list[-2]`获取倒数第二个,等等.最后`some_list[-len(some_list)]`可以获取第一个元素~~ 12 | 13 | 你也可以用这种方法获取列表元素,例如: 14 | 15 | ```python 16 | >>> some_list = [1, 2, 3] 17 | >>> some_list[-1] = 5 # Set the last element 18 | >>> some_list[-2] = 3 # Set the second to last element 19 | >>> some_list 20 | [1, 3, 5] 21 | ``` -------------------------------------------------------------------------------- /data/931092.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 反转字符串 4 | 5 | 在Python里`str`没有内建的`reverse`函数.实现字符串反转最好的方法是什么? 6 | 7 | 如果答案很简单的话,那么最有效的是什么.是不是`str`要转换成一个不同的对象. 8 | 9 | *** 10 | 11 | 这个怎么样: 12 | 13 | ```python 14 | >>> 'hello world'[::-1] 15 | 'dlrow olleh' 16 | ``` 17 | 18 | 这是拓展的[切片](http://docs.python.org/2/whatsnew/2.3.html#extended-slices)语法.用`[begin:end:step]`实现-从begin开始到end结束步长是-1的话就可以反转一个字符串. -------------------------------------------------------------------------------- /data/9371238.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 为什么在C++中读取stdin中的行会比Python慢呢? 4 | 5 | ps:这个是C++的问题了所以没做翻译. -------------------------------------------------------------------------------- /data/952914.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 在嵌套列表中获取 flat list 4 | 5 | 我好奇如何可以 flat 一个嵌套列表. 6 | 7 | 我可以用 for 循环来做, 但是有没有更好的方法?我试着用 reduce , 但是失败了 8 | 9 | Code 10 | 11 | ```python 12 | l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] 13 | reduce(lambda x, y: x.extend(y), l) 14 | ``` 15 | 16 | Error message 17 | 18 | ```python 19 | Traceback (most recent call last): 20 | File "", line 1, in 21 | File "", line 1, in 22 | AttributeError: 'NoneType' object has no attribute 'extend' 23 | ``` 24 | 25 | *** 26 | 27 | ```python 28 | flat_list = [item for sublist in l for item in sublist] 29 | ``` 30 | 31 | 等价于 32 | 33 | ```python 34 | for sublist in l: 35 | for item in sublist: 36 | flat_list.append(item) 37 | ``` 38 | 39 | 这个是完整的写法: 40 | 41 | ```python 42 | flatten = lambda l: [item for sublist in l for item in sublist] 43 | ``` 44 | 45 | 可以用 `timeit` module 来验证效率: 46 | 47 | ```python 48 | $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]' 49 | 10000 loops, best of 3: 143 usec per loop 50 | $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])' 51 | 1000 loops, best of 3: 969 usec per loop 52 | $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)' 53 | 1000 loops, best of 3: 1.1 msec per loop 54 | ``` 55 | -------------------------------------------------------------------------------- /data/9573244.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 检查字符串为空的最优雅的方法 4 | 5 | *** 6 | 7 | 空字符串被认为是 [falsy](http://docs.python.org/2/library/stdtypes.html#truth-value-testing), 意味着转化成布尔类型值为 false, 所以你可以: 8 | 9 | ```python 10 | if not myString: 11 | ``` 12 | 13 | 在 [Truth Value Testing](http://docs.python.org/library/stdtypes.html#truth-value-testing)可以查询到其他变量转化成布尔类型对应的值. -------------------------------------------------------------------------------- /data/961632.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 整数转化为字符串 4 | 5 | 我希望将整数转为 string,我试了如下方法: 6 | 7 | ```python 8 | d = 15 9 | d.str() 10 | ``` 11 | 12 | 但是提示 `int` 没有 `str` 方法 13 | 14 | *** 15 | 16 | ```python 17 | 1641 18 | down vote 19 | accepted 20 | >>> str(10) 21 | '10' 22 | >>> int('10') 23 | 1 24 | ``` 25 | 26 | 文档链接 27 | 28 | * [`int()`](https://docs.python.org/2/library/functions.html#int) 29 | * [`str`](https://docs.python.org/2/library/functions.html#str) 30 | 31 | 问题来自这个代码: `d.str()`. 32 | 33 | 转换是使用的内建 `str()` 函数,调用的是其参数的 `__str__()` 方法 -------------------------------------------------------------------------------- /data/986006.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 怎么用引用来改变一个变量? 4 | 5 | Python的文档对参数传递的是值还是引用没有明确说明,下面的代码没有改变值`Original` 6 | 7 | ```python 8 | class PassByReference: 9 | def __init__(self): 10 | self.variable = 'Original' 11 | self.Change(self.variable) 12 | print self.variable 13 | 14 | def Change(self, var): 15 | var = 'Changed' 16 | ``` 17 | 18 | 有什么方法能让通过引用来改变变量吗? 19 | 20 | *** 21 | 22 | 参数是通过assignment来传递的.原因是双重的: 23 | 24 | 1. 传递的参数实际上是一个对象的引用(但是这个引用是通过值传递的) 25 | 2. 一些数据类型是可变的,但有一些就不是. 26 | 27 | 所以: 28 | 29 | * 如果传递一个可变对象到一个方法,方法就会获得那个对象的引用,而你也可以随心所欲的改变它了.但是你在方法里重新绑定了这个引用,外部是无法得知的,而当函数完成后,外界的引用依然指向原来的对象. 30 | * 如果你传递一个不可变的对象到一个方法,你仍然不能在外边重新绑定引用,你连改变对象都不可以. 31 | 32 | 为了弄懂,来几个例子. 33 | 34 | ### 列表-可变类型 35 | 36 | **让我们试着修改当做参数传递给方法的列表**: 37 | 38 | ```python 39 | def try_to_change_list_contents(the_list): 40 | print 'got', the_list 41 | the_list.append('four') 42 | print 'changed to', the_list 43 | 44 | outer_list = ['one', 'two', 'three'] 45 | 46 | print 'before, outer_list =', outer_list 47 | try_to_change_list_contents(outer_list) 48 | print 'after, outer_list =', outer_list 49 | ``` 50 | 51 | 输出: 52 | 53 | ```python 54 | before, outer_list = ['one', 'two', 'three'] 55 | got ['one', 'two', 'three'] 56 | changed to ['one', 'two', 'three', 'four'] 57 | after, outer_list = ['one', 'two', 'three', 'four'] 58 | ``` 59 | 60 | 因为传递的参数是`outer_list`的引用,而不是副本,所以我们可以用可变列表的方法来改变它,而且改变同时反馈到了外部. 61 | 62 | **现在让我们来看看我们试着改变作为传递参数的引用时到底发生了什么:** 63 | 64 | ```python 65 | def try_to_change_list_reference(the_list): 66 | print 'got', the_list 67 | the_list = ['and', 'we', 'can', 'not', 'lie'] 68 | print 'set to', the_list 69 | 70 | outer_list = ['we', 'like', 'proper', 'English'] 71 | 72 | print 'before, outer_list =', outer_list 73 | try_to_change_list_reference(outer_list) 74 | print 'after, outer_list =', outer_list 75 | ``` 76 | 77 | 输出: 78 | 79 | ```python 80 | before, outer_list = ['we', 'like', 'proper', 'English'] 81 | got ['we', 'like', 'proper', 'English'] 82 | set to ['and', 'we', 'can', 'not', 'lie'] 83 | after, outer_list = ['we', 'like', 'proper', 'English'] 84 | ``` 85 | 86 | 既然`the_list`参数是通过值进行传递的,那么为它赋值将会对方法以外没有影响.`the_list`是`outer_list`引用(注意,名词)的一个拷贝,我们将`the_list`指向一个新的列表,但是并没有改变`outer_list`的指向. 87 | 88 | ### 字符串-不可变类型 89 | 90 | **它是不可变类型,所以我们不能改变字符串里的内容.** 91 | 92 | 现在,让我们试着改变引用 93 | 94 | ```python 95 | def try_to_change_string_reference(the_string): 96 | print 'got', the_string 97 | the_string = 'In a kingdom by the sea' 98 | print 'set to', the_string 99 | 100 | outer_string = 'It was many and many a year ago' 101 | 102 | print 'before, outer_string =', outer_string 103 | try_to_change_string_reference(outer_string) 104 | print 'after, outer_string =', outer_string 105 | ``` 106 | 107 | 输出: 108 | 109 | ```python 110 | before, outer_string = It was many and many a year ago 111 | got It was many and many a year ago 112 | set to In a kingdom by the sea 113 | after, outer_string = It was many and many a year ago 114 | ``` 115 | 116 | 又一次,既然`the_string`参数用值进行传递,对它进行赋值并不能改变方法外的值.`the_string`只是`outer_string`引用(名词)的副本,所以我们让`the_string`指向一个新字符串,依然无法改变`outer_string`的指向. 117 | 118 | 希望你清楚以上那些. 119 | 120 | 修改:到现在位置还没有回答"有什么方法同过引用传递变量?",让我们往下看. 121 | 122 | ### 我们该怎么办? 123 | 124 | 你可以返回一个新值.这不会改变传过来的值,但是能得到你想要的结果. 125 | 126 | ```python 127 | def return_a_whole_new_string(the_string): 128 | new_string = something_to_do_with_the_old_string(the_string) 129 | return new_string 130 | 131 | # 你可以像这样调用 132 | my_string = return_a_whole_new_string(my_string) 133 | ``` 134 | 135 | 如果你真的不想用一个返回值,你可以建一个存放你的值的类,然后把它传递给函数或者用一个已有的类,像列表: 136 | 137 | ```python 138 | def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change): 139 | new_string = something_to_do_with_the_old_string(stuff_to_change[0]) 140 | stuff_to_change[0] = new_string 141 | 142 | # 你可以像这样调用 143 | wrapper = [my_string] 144 | use_a_wrapper_to_simulate_pass_by_reference(wrapper) 145 | 146 | do_something_with(wrapper[0]) 147 | ``` 148 | 149 | 虽然看起来有一点笨重,但还是达到你的效果了. -------------------------------------------------------------------------------- /data/990754.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## 如何离开/退出/停用Python的virtualenv? 4 | 5 | 我正在用virtualenv和virtualenvwrapper.我能用命令很好的在virtualenv之间切换. 6 | 7 | ``` 8 | me@mymachine:~$ workon env1 9 | (env1)me@mymachine:~$ workon env2 10 | (env2)me@mymachine:~$ workon env1 11 | (env1)me@mymachine:~$ 12 | ``` 13 | 14 | 但是如何退出虚拟机回到自己的环境中?到目前位置只有一个方法: 15 | 16 | ``` 17 | me@mymachine:~$ 18 | ``` 19 | 20 | 就是退出shell再新建一个.这有点烦人.有没有现成的命令?如果没有我怎么创建它? 21 | 22 | *** 23 | 24 | 通常在虚拟环境中在shell中输入: 25 | 26 | ``` 27 | $ deactivate 28 | ``` 29 | 30 | 将会返回正常环境. -------------------------------------------------------------------------------- /data/9942594.md: -------------------------------------------------------------------------------- 1 | *** 2 | 3 | ## UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128) 4 | 5 | *** 6 | 7 | 你应该去读一读 [Unicode HOWTO](https://docs.python.org/2.7/howto/unicode.html).这是个 [very first example](https://docs.python.org/2.7/howto/unicode.html#the-unicode-type). 8 | 9 | 首先不要用 `str` 来进行 unicode 到 text/byte 的转换. 10 | 11 | 取而代之的使用 [`.encode()`](http://docs.python.org/library/stdtypes.html#str.encode): 12 | 13 | ```python 14 | p.agent_info = u' '.join((agent_contact, agent_telno)).encode('utf-8').strip() 15 | ``` 16 | 17 | -------------------------------------------------------------------------------- /get_so_100.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import requests 5 | import re 6 | 7 | from bs4 import BeautifulSoup 8 | from lxml import etree 9 | import datetime 10 | import time 11 | 12 | URL = "https://stackoverflow.com/questions/tagged/python?page={}&sort=votes&pagesize=15" 13 | PATH = "/Users/limbo/github/stackoverflow_python" 14 | 15 | TEMPLETE = """ 16 | | rank | vote | view | answer | url | 17 | |:-:|:-:|:-:|:-:|:-:| 18 | |{index}|{vote}|{views}|{answers}| [url](http://stackoverflow.com{href}) | 19 | """ 20 | 21 | SUMMARY_TEMPLETE = """ 22 | # Summary 23 | 24 | ## 简介 25 | 26 | * [Introduction](README.md) 27 | 28 | ## TOP 100 29 | 30 | {} 31 | """ 32 | 33 | README_TEMPLETE = """ 34 | # Stackoverflow 上关于 Python 的问题 35 | [![](https://img.shields.io/github/stars/taizilongxu/stackoverflow_python.svg?style=for-the-badge&label=Stars)](https://github.com/taizilongxu/stackoverflow_python) 36 | 37 | 排名根据 vote 数量选取, 许多 SO 上的回答质量确实高, 有能力建议查看原文, 一般引用的文章也非常好, 38 | 39 | 翻译是根据 question id 写在 data 文件夹, 运行脚本 `get_so_100.py` 自动生成 `part` 部分文档 40 | 41 | ## 目录 42 | 43 | > 图表数据更新时间 {} 44 | 45 | | rank | vote | view | answer | url |中文| 46 | |:-:|:-:|:-:|:-:|:-:|:-| 47 | {} 48 | """ 49 | 50 | 51 | def get_page(num): 52 | data = [] 53 | r = requests.get(URL.format(num)) 54 | selector = etree.HTML(r.text) 55 | votes = selector.xpath('//*[@id="questions"]/div/div[1]/div[1]/div[1]/div/span/strong/text()') 56 | views = selector.xpath('//*[@id="questions"]/div/div[1]/div[2]/@title') 57 | titles = selector.xpath('//*[@id="questions"]/div/div[2]/h3/a/text()') 58 | hrefs = selector.xpath('//*[@id="questions"]/div/div[2]/h3/a/@href') 59 | answers = selector.xpath('//*[@id="questions"]/div/div[1]/div[1]/div[2]/strong/text()') 60 | 61 | for vote, view, title, href, answers in zip(votes, views, titles, hrefs, answers): 62 | data.append({ 63 | 'vote': vote, 64 | 'views': get_view(view), 65 | 'title': title, 66 | 'href': href, 67 | 'answers': answers, 68 | 'pid': get_id(href) 69 | }) 70 | 71 | return data 72 | 73 | def get_view(view): 74 | return ''.join(view.split(','))[:-6] 75 | 76 | 77 | def get_id(href): 78 | return href.split('/')[2] 79 | 80 | 81 | def get_100(): 82 | return get_page(1) + get_page(2) 83 | 84 | 85 | def get_content_by_pid(pid): 86 | try: 87 | with open('{}/data/{}.md'.format(PATH, pid), 'r') as F: 88 | return ''.join(F.readlines()) 89 | except Exception as e: 90 | return '' 91 | 92 | def get_tran_title(content): 93 | try: 94 | title = re.search(r"## (.*?)\n", content).group(1) 95 | return title 96 | except Exception as e: 97 | return '' 98 | 99 | 100 | def make_toc(trans_title, file_name): 101 | return "* [{}](part/{})".format(trans_title, file_name) 102 | 103 | 104 | def make_summary(data): 105 | tocs = [] 106 | for index, i in enumerate(data): 107 | content = get_content_by_pid(i['pid']) 108 | file_name = '{}.md'.format(index + 1) 109 | 110 | tocs.append(make_toc(get_tran_title(content), file_name)) 111 | 112 | return SUMMARY_TEMPLETE.format('\n'.join(tocs)) 113 | 114 | def make_readme(data): 115 | lines = [] 116 | for index, i in enumerate(data): 117 | content = get_content_by_pid(i['pid']) 118 | file_name = '{}.md'.format(index + 1) 119 | cn_name = get_tran_title(content) 120 | line = "|{}|{}|{}|{}|[url](http://stackoverflow.com{})|[{}](part/{})|".format(index+1, i['vote'], i['views'], 121 | i['answers'], i['href'], cn_name, file_name) 122 | lines.append(line) 123 | 124 | update_time = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') 125 | return README_TEMPLETE.format(update_time, '\n'.join(lines)) 126 | 127 | def make_summary_file(content): 128 | with open('{}/SUMMARY.md'.format(PATH), 'w') as F: 129 | F.write(content) 130 | 131 | 132 | def make_question_file(content, file_name): 133 | with open('{}/part/{}'.format(PATH, file_name), 'w') as F: 134 | F.write(content) 135 | 136 | 137 | def make_question_files(data): 138 | for index, i in enumerate(data): 139 | i['index'] = index + 1 140 | content = get_content_by_pid(i['pid']) 141 | content = TEMPLETE.format(**i) + content 142 | file_name = '{}.md'.format(index + 1) 143 | 144 | make_question_file(content, file_name) 145 | 146 | def make_readme_file(data): 147 | with open('{}/README.md'.format(PATH), 'w') as F: 148 | F.write(data) 149 | 150 | data = get_100() 151 | 152 | content = make_summary(data) 153 | make_summary_file(content) 154 | 155 | readme = make_readme(data) 156 | make_readme_file(readme) 157 | 158 | make_question_files(data) 159 | -------------------------------------------------------------------------------- /images/2846653-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taizilongxu/stackoverflow_python/3afbaaaa8c9a8d48eae2d72b3cb4efd033e937a4/images/2846653-1.png -------------------------------------------------------------------------------- /part/1.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |1|10373|2269693|41| [url](http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do) | 5 | *** 6 | 7 | 8 | ## Python中关键字yield有什么作用? 9 | 10 | yield有什么用? 11 | 12 | 例如下面这段代码: 13 | 14 | ```python 15 | def node._get_child_candidates(self, distance, min_dist, max_dist): 16 | if self._leftchild and distance - max_dist < self._median: 17 | yield self._leftchild 18 | if self._rightchild and distance + max_dist >= self._median: 19 | yield self._rightchild 20 | ``` 21 | 22 | 下面是调用它: 23 | 24 | ```python 25 | result, candidates = list(), [self] 26 | while candidates: 27 | node = candidates.pop() 28 | distance = node._get_dist(obj) 29 | if distance <= max_dist and distance >= min_dist: 30 | result.extend(node._values) 31 | candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) 32 | return result 33 | ``` 34 | 35 | 当`_get_child_candidates`方法被调用的时候发生了什么?是返回一个列表?还是一个元祖?它还能第二次调用吗?后面的调用什么时候结束? 36 | 37 | *** 38 | 39 | 为了理解yield有什么用,首先得理解generators,而理解generators前还要理解iterables 40 | 41 | #### Iterables 42 | 43 | 当你创建了一个列表,你可以一个一个的读取它的每一项,这叫做iteration: 44 | 45 | ```python 46 | >>> mylist = [1, 2, 3] 47 | >>> for i in mylist: 48 | ... print(i) 49 | 1 50 | 2 51 | 3 52 | ``` 53 | 54 | Mylist是可迭代的.当你用列表推导式的时候,你就创建了一个列表,而这个列表也是可迭代的: 55 | 56 | ```python 57 | >>> mylist = [x*x for x in range(3)] 58 | >>> for i in mylist: 59 | ... print(i) 60 | 0 61 | 1 62 | 4 63 | ``` 64 | 65 | 所有你可以用在`for...in...`语句中的都是可迭代的:比如lists,strings,files...因为这些可迭代的对象你可以随意的读取所以非常方便易用,但是你必须把它们的值放到内存里,当它们有很多值时就会消耗太多的内存. 66 | 67 | #### Generators 68 | 69 | 生成器也是迭代器的一种,但是你**只能迭代它们一次**.原因很简单,因为它们不是全部存在内存里,它们只在要调用的时候在内存里生成: 70 | 71 | ```python 72 | >>> mygenerator = (x*x for x in range(3)) 73 | >>> for i in mygenerator: 74 | ... print(i) 75 | 0 76 | 1 77 | 4 78 | ``` 79 | 80 | 生成器和迭代器的区别就是用`()`代替`[]`,还有你不能用`for i in mygenerator`第二次调用生成器:首先计算0,然后会在内存里丢掉0去计算1,直到计算完4. 81 | 82 | #### Yield 83 | 84 | `Yield`的用法和关键字`return`差不多,下面的函数将会返回一个生成器: 85 | 86 | ```python 87 | >>> def createGenerator(): 88 | ... mylist = range(3) 89 | ... for i in mylist: 90 | ... yield i*i 91 | ... 92 | >>> mygenerator = createGenerator() # 创建生成器 93 | >>> print(mygenerator) # mygenerator is an object! 94 | 95 | >>> for i in mygenerator: 96 | ... print(i) 97 | 0 98 | 1 99 | 4 100 | ``` 101 | 102 | 在这里这个例子好像没什么用,不过当你的函数要返回一个非常大的集合并且你希望只读一次的话,那么它就非常的方便了. 103 | 104 | 要理解`Yield`你必须先理解当你调用函数的时候,函数里的代码并没有运行.函数仅仅返回生成器对象,这就是它最微妙的地方:-) 105 | 106 | 然后呢,每当`for`语句迭代生成器的时候你的代码才会运转. 107 | 108 | 现在,到了最难的部分: 109 | 110 | 当`for`语句第一次调用函数里返回的生成器对象,函数里的代码就开始运作,直到碰到`yield`,然后会返回本次循环的第一个返回值.所以下一次调用也将运行一次循环然后返回下一个值,直到没有值可以返回. 111 | 112 | 一旦函数运行并且没有碰到`yeild`语句就认为生成器已经为空了.原因有可能是循环结束或者没有满足`if/else`之类的. 113 | 114 | #### 对于你的代码的解释 115 | 116 | 生成器: 117 | 118 | ```python 119 | 120 | # 这里你创建node方法的对象将会返回一个生成器 121 | def node._get_child_candidates(self, distance, min_dist, max_dist): 122 | 123 | # 这里的代码你每次使用生成器对象的时候将会调用 124 | 125 | if self._leftchild and distance - max_dist < self._median: 126 | yield self._leftchild 127 | 128 | if self._rightchild and distance + max_dist >= self._median: 129 | yield self._rightchild 130 | 131 | # 如果代码运行到这里,生成器就被认为变成了空的 132 | ``` 133 | 134 | 调用: 135 | 136 | ```python 137 | # 创建空列表和一个当前对象索引的列表 138 | result, candidates = list(), [self] 139 | 140 | # 在candidates上进行循环(在开始只保含一个元素) 141 | while candidates: 142 | 143 | # 获得最后一个condidate然后从列表里删除 144 | node = candidates.pop() 145 | 146 | # 获取obj和candidate的distance 147 | distance = node._get_dist(obj) 148 | 149 | # 如果distance何时将会填入result 150 | if distance <= max_dist and distance >= min_dist: 151 | result.extend(node._values) 152 | 153 | candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) 154 | 155 | return result 156 | ``` 157 | 158 | 这段代码有几个有意思的地方: 159 | 160 | * 一般的时候我们会在循环迭代一个列表的同时在列表中添加元素:-)尽管在有限循环里结束多少有一些危险,但也不失为一个简单的方法去遍历嵌套的数据.在这里`candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))`将遍历生成器的每一个值,但是`while`循环中的condidates将不再保存已经遍历过的生成器对象,也就是说添加进condidates的生成器对象只会遍历一遍。 161 | 162 | * `extend()`是一个列表对象的方法,它可以把一个迭代对象添加进列表. 163 | 164 | 我们经常这么用: 165 | 166 | ```python 167 | >>> a = [1, 2] 168 | >>> b = [3, 4] 169 | >>> a.extend(b) 170 | >>> print(a) 171 | [1, 2, 3, 4] 172 | ``` 173 | 174 | 但是在你给的代码里得到的是生成器,这样做的好处: 175 | 176 | 1. 你不需要读这个值两次 177 | 2. 你能得到许多孩子节点但是你不希望他们全部存入内存. 178 | 179 | 这种方法之所以能很好的运行是因为Python不关心方法的参数是不是一个列表.它只希望接受一个迭代器,所以不管是strings,lists,tuples或者generators都可以!这种方法叫做duck typing,这也是Python看起来特别cool的原因之一.但是这又是另外一个传说了,另一个问题 180 | 181 | 好了,看到这里可以打住了,下面让我们看看生成器的高级用法: 182 | 183 | #### 控制迭代器的穷尽 184 | 185 | ```python 186 | >>> class Bank(): # 让我们建个银行,生产许多ATM 187 | ... crisis = False 188 | ... def create_atm(self): 189 | ... while not self.crisis: 190 | ... yield "$100" 191 | >>> hsbc = Bank() # 当一切就绪了你想要多少ATM就给你多少 192 | >>> corner_street_atm = hsbc.create_atm() 193 | >>> print(corner_street_atm.next()) 194 | $100 195 | >>> print(corner_street_atm.next()) 196 | $100 197 | >>> print([corner_street_atm.next() for cash in range(5)]) 198 | ['$100', '$100', '$100', '$100', '$100'] 199 | >>> hsbc.crisis = True # cao,经济危机来了没有钱了! 200 | >>> print(corner_street_atm.next()) 201 | 202 | >>> wall_street_atm = hsbc.create_atm() # 对于其他ATM,它还是True 203 | >>> print(wall_street_atm.next()) 204 | 205 | >>> hsbc.crisis = False # 麻烦的是,尽管危机过去了,ATM还是空的 206 | >>> print(corner_street_atm.next()) 207 | 208 | >>> brand_new_atm = hsbc.create_atm() # 只能重新新建一个bank了 209 | >>> for cash in brand_new_atm: 210 | ... print cash 211 | $100 212 | $100 213 | $100 214 | $100 215 | $100 216 | $100 217 | $100 218 | $100 219 | $100 220 | ... 221 | ``` 222 | 223 | 它对于一些不断变化的值很有用,比如说用来控制资源的访问. 224 | 225 | #### Itertools,你的好基友 226 | 227 | itertools模块包含了一些特殊的函数可以操作可迭代对象.有没有想过复制一个生成器?链接两个生成器?把嵌套列表里的值组织成一个列表?Map/Zip还不用创建另一个列表? 228 | 229 | 来吧`import itertools` 230 | 231 | 来一个例子?让我们看看4匹马比赛有多少个排名结果: 232 | 233 | ```python 234 | >>> horses = [1, 2, 3, 4] 235 | >>> races = itertools.permutations(horses) 236 | >>> print(races) 237 | 238 | >>> print(list(itertools.permutations(horses))) 239 | [(1, 2, 3, 4), 240 | (1, 2, 4, 3), 241 | (1, 3, 2, 4), 242 | (1, 3, 4, 2), 243 | (1, 4, 2, 3), 244 | (1, 4, 3, 2), 245 | (2, 1, 3, 4), 246 | (2, 1, 4, 3), 247 | (2, 3, 1, 4), 248 | (2, 3, 4, 1), 249 | (2, 4, 1, 3), 250 | (2, 4, 3, 1), 251 | (3, 1, 2, 4), 252 | (3, 1, 4, 2), 253 | (3, 2, 1, 4), 254 | (3, 2, 4, 1), 255 | (3, 4, 1, 2), 256 | (3, 4, 2, 1), 257 | (4, 1, 2, 3), 258 | (4, 1, 3, 2), 259 | (4, 2, 1, 3), 260 | (4, 2, 3, 1), 261 | (4, 3, 1, 2), 262 | (4, 3, 2, 1)] 263 | ``` 264 | 265 | #### 理解迭代的内部机制 266 | 267 | 迭代是可迭代对象(对应`__iter__()`方法)和迭代器(对应`__next__()`方法)的一个过程.可迭代对象就是任何你可以迭代的对象(废话啊).迭代器就是可以让你迭代可迭代对象的对象(有点绕口,意思就是这个意思) 268 | 269 | 预知后事如何,请看[for 循环是如何工作的](http://effbot.org/zone/python-for-statement.htm) 270 | 271 | 272 | -------------------------------------------------------------------------------- /part/10.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |10|3647|795254|27| [url](http://stackoverflow.com/questions/136097/difference-between-staticmethod-and-classmethod) | 5 | *** 6 | 7 | ## 装饰器@staticmethod和@classmethod有什么区别? 8 | 9 | *** 10 | 11 | 也许一些例子会有帮助:注意`foo`, `class_foo` 和`static_foo`参数的区别: 12 | 13 | ```python 14 | class A(object): 15 | def foo(self,x): 16 | print "executing foo(%s,%s)"%(self,x) 17 | 18 | @classmethod 19 | def class_foo(cls,x): 20 | print "executing class_foo(%s,%s)"%(cls,x) 21 | 22 | @staticmethod 23 | def static_foo(x): 24 | print "executing static_foo(%s)"%x 25 | 26 | a=A() 27 | ``` 28 | 29 | 下面是一个对象实体调用方法的常用方式.对象实体`a`被隐藏的传递给了第一个参数. 30 | 31 | ```python 32 | a.foo(1) 33 | # executing foo(<__main__.A object at 0xb7dbef0c>,1) 34 | ``` 35 | 36 | 用**classmethods**装饰,隐藏的传递给第一个参数的是对象实体的类(`class A`)而不是`self`. 37 | 38 | ```python 39 | a.class_foo(1) 40 | # executing class_foo(,1) 41 | ``` 42 | 43 | 你也可以用类调用`class_foo`.实际上,如果你把一些方法定义成`classmethod`,那么实际上你是希望用类来调用这个方法,而不是用这个类的实例来调用这个方法.`A.foo(1)`将会返回一个`TypeError`错误,` A.class_foo(1)`将会正常运行: 44 | 45 | ```python 46 | A.class_foo(1) 47 | # executing class_foo(,1) 48 | ``` 49 | 50 | One use people have found for class methods is to create inheritable alternative constructors. 51 | 52 | 用**staticmethods**来装饰,不管传递给第一个参数的是`self`(对象实体)还是`cls`(类).它们的表现都一样: 53 | 54 | ```python 55 | a.static_foo(1) 56 | # executing static_foo(1) 57 | 58 | A.static_foo('hi') 59 | # executing static_foo(hi) 60 | ``` 61 | 62 | 静态方法被用来组织类之间有逻辑关系的函数. 63 | 64 | `foo`只是个函数,但是当你调用`a.foo`的时候你得到的不仅仅是一个函数,你得到的是一个第一个参数绑定到`a`的"加强版"函数.`foo`需要两个参数,而`a.foo`仅仅需要一个参数. 65 | 66 | `a`绑定了`foo`.下面可以知道什么叫"绑定"了: 67 | 68 | ```python 69 | print(a.foo) 70 | # > 71 | ``` 72 | 73 | 如果使用`a.class_foo`,是`A`绑定到了`class_foo`而不是`a`. 74 | 75 | ```python 76 | print(a.class_foo) 77 | # > 78 | ``` 79 | 80 | 最后剩下静态方法,说到底它就是一个方法.`a.static_foo`只是返回一个不带参数绑定的方法.`static_foo`和`a.static_foo`只需要一个参数. 81 | 82 | ```python 83 | print(a.static_foo) 84 | # 85 | ``` -------------------------------------------------------------------------------- /part/100.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |100|1321|677783|11| [url](http://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python) | 5 | -------------------------------------------------------------------------------- /part/11.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |11|3599|4214927|10| [url](http://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method) | 5 | *** 6 | 7 | ## Python中有检查字符串包含的方法吗? 8 | 9 | 我正在找`string.contains`或者`string.indexof`方法. 10 | 11 | 我希望: 12 | 13 | ```python 14 | if not somestring.contains("blah"): 15 | continue 16 | ``` 17 | 18 | *** 19 | 20 | 你可以用`in`啊: 21 | 22 | ```python 23 | if not "blah" in somestring: continue 24 | ``` 25 | 26 | 或者: 27 | 28 | ```python 29 | if "blah" not in somestring: continue 30 | ``` -------------------------------------------------------------------------------- /part/12.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |12|3494|2274525|41| [url](http://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) | 5 | *** 6 | 7 | ## 在嵌套列表中获取 flat list 8 | 9 | 我好奇如何可以 flat 一个嵌套列表. 10 | 11 | 我可以用 for 循环来做, 但是有没有更好的方法?我试着用 reduce , 但是失败了 12 | 13 | Code 14 | 15 | ```python 16 | l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] 17 | reduce(lambda x, y: x.extend(y), l) 18 | ``` 19 | 20 | Error message 21 | 22 | ```python 23 | Traceback (most recent call last): 24 | File "", line 1, in 25 | File "", line 1, in 26 | AttributeError: 'NoneType' object has no attribute 'extend' 27 | ``` 28 | 29 | *** 30 | 31 | ```python 32 | flat_list = [item for sublist in l for item in sublist] 33 | ``` 34 | 35 | 等价于 36 | 37 | ```python 38 | for sublist in l: 39 | for item in sublist: 40 | flat_list.append(item) 41 | ``` 42 | 43 | 这个是完整的写法: 44 | 45 | ```python 46 | flatten = lambda l: [item for sublist in l for item in sublist] 47 | ``` 48 | 49 | 可以用 `timeit` module 来验证效率: 50 | 51 | ```python 52 | $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]' 53 | 10000 loops, best of 3: 143 usec per loop 54 | $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])' 55 | 1000 loops, best of 3: 969 usec per loop 56 | $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)' 57 | 1000 loops, best of 3: 1.1 msec per loop 58 | ``` 59 | -------------------------------------------------------------------------------- /part/13.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |13|3472|4533564|21| [url](http://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory) | 5 | *** 6 | 7 | ## 在Python中列出目录中的所有文件 8 | 9 | 怎么样用Python列出一个目录的所有文件并且存进一个列表? 10 | 11 | *** 12 | 13 | [`os.listdir()`](http://docs.python.org/library/os.html#os.listdir)可以获得一个目录中所有文件或者子目录. 14 | 15 | 如果你只想要文件的话,你也可以用`os.path`把其他的过滤掉: 16 | 17 | ```python 18 | from os import listdir 19 | from os.path import isfile, join 20 | onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ] 21 | ``` 22 | 或者你可以用[`os.walk()`](http://docs.python.org/library/os.html#os.walk),它遍历每个目录将会返回两个列表(一个文件列表,一个目录列表),如果你想要顶层目录只需要在第一次迭代后break一下即可. 23 | 24 | ```python 25 | from os import walk 26 | 27 | f = [] 28 | for (dirpath, dirnames, filenames) in walk(mypath): 29 | f.extend(filenames) 30 | break 31 | ``` 32 | 33 | 最后,如果你想增加列表可以像上面那样用`.extend()`或者: 34 | 35 | ```python 36 | >>> q = [1,2,3] 37 | >>> w = [4,5,6] 38 | >>> q = q + w 39 | >>> q 40 | [1,2,3,4,5,6] 41 | ``` 42 | 43 | 我个人更喜欢`.extend()`# 在Python中列出目录中的所有文件 44 | 45 | -------------------------------------------------------------------------------- /part/14.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |14|3420|2948940|34| [url](http://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) | 5 | *** 6 | 7 | ## 用字典的值(key)对字典进行排序 8 | 9 | 我有个字典,字典的值来自于数据库:一个是字符串,一个是数字.字符串是唯一的,所以键(key)就是字符串. 10 | 11 | 我可以用键(key)来排序,但是怎么用值(value)来排序呢? 12 | 13 | 注:我已经看过另一个问题[怎样对列表中的字典的键值(key)对字典进行排序?](http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary-in-python),或许这种方法可以,但是我确实只需要一个字典,我想看看还有其他更好的方法. 14 | 15 | *** 16 | 17 | 对字典进行排序是不可能的,只有把字典转换成另一种方式才能排序.字典本身是无序的,但是像列表元组等其他类型是有序的.所以你需要用一个元组列表来表示排序的字典. 18 | 19 | 例子: 20 | 21 | ```python 22 | import operator 23 | x = {1: 2, 3: 4, 4:3, 2:1, 0:0} 24 | sorted_x = sorted(x.items(), key=operator.itemgetter(1)) 25 | ``` 26 | 27 | `sorted_x`是一个元组列表,用每个元组的第二个元素进行排序.`dict(sorted_x) == x`. 28 | 29 | 如果想要用键(key)来进行排序: 30 | 31 | ``` 32 | import operator 33 | x = {1: 2, 3: 4, 4:3, 2:1, 0:0} 34 | sorted_x = sorted(x.items(), key=operator.itemgetter(0)) 35 | ``` 36 | 37 | *** 38 | 39 | 你也可以: 40 | 41 | ``` 42 | sorted(d.items(), key=lambda x: x[1]) 43 | ``` 44 | 45 | -------------------------------------------------------------------------------- /part/15.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |15|3400|1805051|33| [url](http://stackoverflow.com/questions/509211/understanding-slice-notation) | 5 | *** 6 | 7 | ## 理解Python切片 8 | 9 | 对于Python的切片有什么好的资料吗?对我来说理解切片有点难度.它看起来非常有用,但是我还是不能理解它,我正在找有什么好的资料. 10 | 11 | *** 12 | 13 | 非常简单: 14 | 15 | ```python 16 | a[start:end] # 从start开始到end-1结束 17 | a[start:] # 从start开始直到末尾 18 | a[:end] # 从头部开始直到end结束 19 | a[:] # 复制整个列表 20 | ``` 21 | 22 | 这里还有一个`step`值,可以用在上面素有例子的后面: 23 | 24 | ```python 25 | a[start:end:step] # 按照step步长直到end-1结束,并不是从start一个个遍历到end 26 | ``` 27 | 28 | 重点需要记住的是:`:end`值代表的是不被选中的第一个位置.所以`end`和`start`区别在于选中的元素(如果`step`默认为1) 29 | 30 | 另一点要说的是`start`或者`end`可能是个负数,也就是从尾部而不是从头部开始计数.所以: 31 | 32 | ```python 33 | a[-1] # 列表最后一个元素 34 | a[-2:] # 列表最后两个元素 35 | a[:-2] # 除了最后两个元素剩下的部分 36 | ``` 37 | 如果你调用的元素多于列表中含有的元素个数,Python也会很友好的表示.例如,如果你请求`a[:-2]`而`a`只含有一个元素,你得到的是一个空列表而不是一个错误信息.有些时候你可能更希望得到这个错误信息,所以你得意识到上面的事可能发生. 38 | 39 | 40 | -------------------------------------------------------------------------------- /part/16.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |16|3261|3993138|30| [url](http://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list) | 5 | *** 6 | 7 | ## 查找列表中某个元素的下标 8 | 9 | 比如`["foo","bar","baz"]`和它的一个元素`"bar"`,用什么方法能找到它的下标(1)? 10 | 11 | *** 12 | 13 | ```python 14 | >>> ["foo","bar","baz"].index('bar') 15 | 1 16 | ``` 17 | 18 | 参考资料:[Data Structures > More on Lists](http://docs.python.org/2/tutorial/datastructures.html#more-on-lists) -------------------------------------------------------------------------------- /part/17.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |17|3234|2979757|27| [url](http://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty) | 5 | *** 6 | 7 | ## 检查列表是否为空的最好方法 8 | 9 | 例如,传递下面: 10 | 11 | ``` 12 | a = [] 13 | ``` 14 | 15 | 我怎么检查`a`是空值? 16 | 17 | *** 18 | 19 | ```python 20 | if not a: 21 | print "List is empty" 22 | ``` 23 | 24 | 用隐藏的空列表的布尔值才是最Pythonic的方法. -------------------------------------------------------------------------------- /part/18.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |18|3209|4373538|12| [url](http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) | 5 | *** 6 | 7 | ## 使用 for 来迭代字典的原理 8 | 9 | 有点不理解下面的代码: 10 | 11 | ```python 12 | d = {'x': 1, 'y': 2, 'z': 3} 13 | for key in d: 14 | print key, 'corresponds to', d[key] 15 | ``` 16 | 17 | 我有点不理解 `key` 的部分. Python 是怎么识别出只需要从字典中读取 key? `key` 是 Python 里的关键词还是只是一个简单的变量? 18 | 19 | *** 20 | 21 | `key` 就是一个变量名. 22 | 23 | ```python 24 | for key in d: 25 | ``` 26 | 27 | 上面的语句紧紧会循环字典中的 key ,而不是 key 和 value.如果需要循环 key 和 value, 你可以用下面的方法: 28 | 29 | Python 2.x: 30 | 31 | ```python 32 | for key, value in d.iteritems(): 33 | ``` 34 | 35 | Python 3.x: 36 | 37 | ```python 38 | for key, value in d.items(): 39 | ``` 40 | 41 | 你可以自己试一下用其他变量替换 `key`. 42 | 43 | 在 Python3 里 `iteritems()` 简化成了 `items()`, 它能像 `iteritems()`一样返回一个基于字典本身的像 set 一样的 view, 但是做了更多的优化.在 Python 2.7 里和 `viewitems()` 的效果是一样的. 44 | 45 | 在 Python2 和 Python3 里都有 `items()`, 但是在 2 中只会返回一个 list, 它的结构是这种 `(key, value)` 键值对的形式, 它不能反映出在字典调用 `items()` 后做出的改变.所以在 Python3.x 中需要使用 `list(d.items())` 才能与之等价. -------------------------------------------------------------------------------- /part/19.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |19|3172|3231767|19| [url](http://stackoverflow.com/questions/423379/using-global-variables-in-a-function) | 5 | *** 6 | 7 | ## 如何在一个函数里用全局变量? 8 | 9 | 如果我在一个函数里建了一个全局变量,那么我怎么在另一个函数里使用这个全局变量? 10 | 11 | 我需要把这个全局变量赋值给这个函数的局部变量吗? 12 | 13 | *** 14 | 15 | 如果你要在别的函数里使用全局变量,只要在被调用全局变量函数的里事先用`global`声明一下: 16 | 17 | ```python 18 | globvar = 0 19 | 20 | def set_globvar_to_one(): 21 | global globvar # 需要用global修饰一下globvar 22 | globvar = 1 23 | 24 | def print_globvar(): 25 | print globvar # 如果要读globbar的值的话不需要用global修饰 26 | 27 | set_globvar_to_one() 28 | print_globvar() # 输出 1 29 | ``` 30 | 31 | 我猜正是因为全局变量比较危险,所以Python为了确保你真的知道它是全局变量,所以需要加一个`global`关键字. 32 | 33 | -------------------------------------------------------------------------------- /part/2.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |2|6191|3048629|33| [url](http://stackoverflow.com/questions/419163/what-does-if-name-main-do) | 5 | *** 6 | 7 | ## `if __name__ == "__main__":`有什么作用? 8 | 9 | ```python 10 | # Threading example 11 | import time, thread 12 | 13 | def myfunction(string, sleeptime, lock, *args): 14 | while True: 15 | lock.acquire() 16 | time.sleep(sleeptime) 17 | lock.release() 18 | time.sleep(sleeptime) 19 | 20 | if __name__ == "__main__": 21 | lock = thread.allocate_lock() 22 | thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) 23 | thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) 24 | ``` 25 | 26 | *** 27 | 28 | 当 Python 解析器读取一个源文件时, 会执行里面所有的代码. 29 | 30 | 但是在它执行之前会定义一些特殊的变量.例如,如果 Python 解析器把一个 module(the source file)当成主程序来执行的话, 它会把 `__name__` 的值设置成为 `__main__`.如果这个文件是被其他 module 引入的, `__name__`的名字将会被设成 module 的名字. 31 | 32 | 在你给的例子中, 我们假设作为一个主程序来执行, 例如在 shell 里执行如下命令 33 | 34 | ```shell 35 | python threading_example.py 36 | ``` 37 | 38 | 当设置好特殊变量后, 它会执行 `import` 声明并且开始载入这些 modules.它会执行 `def` 代码块, 创建一个函数对象并且会创建一个 `myfunction` 的变量指向这个函数对象.接下来它会读取 `if` 语句并且判断 `__name__` 是否等于 `__main__`, 如果等于就执行代码块里面的程序. 39 | 40 | 你想创建一个 module (一个 `.py` 文件), 同时也想能够被其他 module 引用.填入 `if __name__ == "__main__":` 能使你在以这个 module 作为主程序时才会执行, 而其他外部引用不会执行这些代码. 41 | 42 | 可以在 [这里](http://ibiblio.org/g2swap/byteofpython/read/module-name.html) 查看更多细节 -------------------------------------------------------------------------------- /part/20.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |20|3116|2973556|20| [url](http://stackoverflow.com/questions/252703/what-is-the-difference-between-pythons-list-methods-append-and-extend) | 5 | *** 6 | 7 | ## Python中的appen和extend 8 | 9 | `append`和`extend`有什么区别? 10 | 11 | *** 12 | 13 | append: 14 | 15 | ```python 16 | x = [1, 2, 3] 17 | x.append([4, 5]) 18 | print (x) 19 | ``` 20 | 21 | 输出:`[1, 2, 3, [4, 5]]` 22 | 23 | extend: 24 | 25 | ```python 26 | x = [1, 2, 3] 27 | x.extend([4, 5]) 28 | print (x) 29 | ``` 30 | 31 | 输出:`[1, 2, 3, 4, 5]` -------------------------------------------------------------------------------- /part/21.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |21|2965|3365658|42| [url](http://stackoverflow.com/questions/415511/how-to-get-the-current-time-in-python) | 5 | *** 6 | 7 | ## 在Python里获取当前时间 8 | 9 | 用什么方法或者模块获取当前时间? 10 | 11 | *** 12 | 13 | ```python 14 | >>> import datetime 15 | >>> datetime.datetime.now() 16 | datetime(2009, 1, 6, 15, 8, 24, 78915) 17 | ``` 18 | 19 | 如果只要时间: 20 | 21 | ```python 22 | >>> datetime.datetime.time(datetime.datetime.now()) 23 | datetime.time(15, 8, 24, 78915) 24 | ``` 25 | 26 | 同样功能但是更紧凑的写法: 27 | 28 | ```python 29 | >>> datetime.datetime.now().time() 30 | ``` 31 | 32 | 获取更多信息,看[文档](http://docs.python.org/library/datetime.html). 33 | 34 | 如果还要节省输出,可以在从`datetime`模块import`datetime`对象: 35 | 36 | ```python 37 | >>> from datetime import datetime 38 | ``` 39 | 40 | 然后把所有`datetime.`从头部去掉. -------------------------------------------------------------------------------- /part/22.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |22|2822|857366|5| [url](http://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block) | 5 | *** 6 | 7 | ## 在一行里获取多个异常 8 | 9 | 我知道这样: 10 | 11 | ```python 12 | try: 13 | # 可能错的地方 14 | except: 15 | # 如果错了执行这里 16 | ``` 17 | 18 | 也知道这样: 19 | 20 | ```python 21 | try: 22 | # 可能错的地方 23 | except IDontLikeYourFaceException: 24 | # 给爷笑一个 25 | except YouAreTooShortException: 26 | # 踩高跷 27 | ``` 28 | 29 | 但是我想在两个不同的异常里做同样的事,我能想到的办法: 30 | 31 | ```python 32 | try: 33 | # 可能错的地方 34 | except IDontLIkeYouException: 35 | # 滚 36 | except YouAreBeingMeanException: 37 | # 滚 38 | ``` 39 | 40 | 有什么方法能像下面那样: 41 | 42 | ```python 43 | try: 44 | # 可能错的地方 45 | except IDontLIkeYouException, YouAreBeingMeanException: 46 | # 滚 47 | ``` 48 | 49 | 现在下面的代码根本不好使: 50 | 51 | ```python 52 | try: 53 | # 可能错的地方 54 | except Exception, e: 55 | # 滚 56 | ``` 57 | 58 | 所以有什么方法可以完成我的要求吗? 59 | 60 | *** 61 | 62 | 用括号扩起来: 63 | 64 | ```python 65 | except (IDontLIkeYouException, YouAreBeingMeanException) as e: 66 | pass 67 | ``` 68 | 69 | 用逗号分割的方法只能在Python2.6和2.7里好使,在Python3中则无效;现在,你应当使用`as`. 70 | -------------------------------------------------------------------------------- /part/23.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |23|2775|681510|22| [url](http://stackoverflow.com/questions/1436703/difference-between-str-and-repr) | 5 | *** 6 | 7 | ## `__str__`和`repr__`的区别 8 | 9 | `__str__`和`repr__`有什么区别? 10 | 11 | *** 12 | 13 | 首先让我们梳理一下张三的答案: 14 | 15 | * 用起来没有什么区别 16 | * `__repr__`的目的是明确的 17 | * `__str__`的目的是可读性 18 | * `__str__`的用法包含`__repr__` 19 | 20 | #### 用法没有什么区别 21 | 22 | 因为Python的宗旨是易用的,所以这看起来有点不寻常.但是当 -------------------------------------------------------------------------------- /part/25.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |25|2774|3086312|13| [url](http://stackoverflow.com/questions/510348/how-can-i-make-a-time-delay-in-python) | 5 | *** 6 | 7 | ## 在 Python 里如何手工进行延迟? 8 | 9 | *** 10 | 11 | ```python 12 | import time 13 | time.sleep(5) # Delays for 5 seconds. You can also use a float value. 14 | ``` 15 | 16 | 这里有另一个例子展示每隔差不多一分钟运行一次: 17 | 18 | ```python 19 | import time 20 | while True: 21 | print("This prints once a minute.") 22 | time.sleep(60) # Delay for 1 minute (60 seconds). 23 | ``` -------------------------------------------------------------------------------- /part/26.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |26|2686|3539652|16| [url](http://stackoverflow.com/questions/1024847/how-can-i-add-new-keys-to-a-dictionary) | 5 | *** 6 | 7 | ## 字典里添加元素的方法 8 | 9 | 当一个字典被创建了,能不能在字典里计入一个键?好像没有`.add()`的方法. 10 | 11 | *** 12 | 13 | ```python 14 | >>> d = {'key':'value'} 15 | >>> print d 16 | {'key': 'value'} 17 | >>> d['mynewkey'] = 'mynewvalue' 18 | >>> print d 19 | {'mynewkey': 'mynewvalue', 'key': 'value'} 20 | ``` 21 | 22 | *** 23 | 24 | ```python 25 | >>> x = {1:2} 26 | >>> print x 27 | {1: 2} 28 | 29 | >>> x.update({3:4}) 30 | >>> print x 31 | {1: 2, 3: 4} 32 | ``` -------------------------------------------------------------------------------- /part/27.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |27|2683|3728780|16| [url](http://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary) | 5 | *** 6 | 7 | ## 检查一个键在字典中是否存在 8 | 9 | 在更新字典之前想检查键是否存在.我写了如下代码: 10 | 11 | ```python 12 | if 'key1' in dict.keys(): 13 | print "blah" 14 | else: 15 | print "boo" 16 | ``` 17 | 18 | 我想这不是最好的方法,还有什么更好的方法? 19 | 20 | *** 21 | 22 | 用`in`. 23 | 24 | ```python 25 | d = dict() 26 | 27 | for i in xrange(100): 28 | key = i % 10 29 | if key in d: 30 | d[key] += 1 31 | else: 32 | d[key] = 1 33 | ``` 34 | 35 | 如果你想要一个默认值,你可以用`dict.get()`: 36 | 37 | ```python 38 | d = dict() 39 | 40 | for i in xrange(100): 41 | key = i % 10 42 | d[key] = d.get(key, 0) + 1 43 | ``` 44 | 45 | 如果相对所有值设置默认值可以用`collections`模块的`defaultdict`函数: 46 | 47 | ```python 48 | from collections import defaultdict 49 | 50 | d = defaultdict(lambda: 0) 51 | 52 | for i in xrange(100): 53 | d[i % 10] += 1 54 | ``` 55 | 56 | 但是总而言之`in`是最好的方法. -------------------------------------------------------------------------------- /part/28.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |28|2676|1390524|27| [url](http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) | 5 | *** 6 | 7 | ## 怎么用引用来改变一个变量? 8 | 9 | Python的文档对参数传递的是值还是引用没有明确说明,下面的代码没有改变值`Original` 10 | 11 | ```python 12 | class PassByReference: 13 | def __init__(self): 14 | self.variable = 'Original' 15 | self.Change(self.variable) 16 | print self.variable 17 | 18 | def Change(self, var): 19 | var = 'Changed' 20 | ``` 21 | 22 | 有什么方法能让通过引用来改变变量吗? 23 | 24 | *** 25 | 26 | 参数是通过assignment来传递的.原因是双重的: 27 | 28 | 1. 传递的参数实际上是一个对象的引用(但是这个引用是通过值传递的) 29 | 2. 一些数据类型是可变的,但有一些就不是. 30 | 31 | 所以: 32 | 33 | * 如果传递一个可变对象到一个方法,方法就会获得那个对象的引用,而你也可以随心所欲的改变它了.但是你在方法里重新绑定了这个引用,外部是无法得知的,而当函数完成后,外界的引用依然指向原来的对象. 34 | * 如果你传递一个不可变的对象到一个方法,你仍然不能在外边重新绑定引用,你连改变对象都不可以. 35 | 36 | 为了弄懂,来几个例子. 37 | 38 | ### 列表-可变类型 39 | 40 | **让我们试着修改当做参数传递给方法的列表**: 41 | 42 | ```python 43 | def try_to_change_list_contents(the_list): 44 | print 'got', the_list 45 | the_list.append('four') 46 | print 'changed to', the_list 47 | 48 | outer_list = ['one', 'two', 'three'] 49 | 50 | print 'before, outer_list =', outer_list 51 | try_to_change_list_contents(outer_list) 52 | print 'after, outer_list =', outer_list 53 | ``` 54 | 55 | 输出: 56 | 57 | ```python 58 | before, outer_list = ['one', 'two', 'three'] 59 | got ['one', 'two', 'three'] 60 | changed to ['one', 'two', 'three', 'four'] 61 | after, outer_list = ['one', 'two', 'three', 'four'] 62 | ``` 63 | 64 | 因为传递的参数是`outer_list`的引用,而不是副本,所以我们可以用可变列表的方法来改变它,而且改变同时反馈到了外部. 65 | 66 | **现在让我们来看看我们试着改变作为传递参数的引用时到底发生了什么:** 67 | 68 | ```python 69 | def try_to_change_list_reference(the_list): 70 | print 'got', the_list 71 | the_list = ['and', 'we', 'can', 'not', 'lie'] 72 | print 'set to', the_list 73 | 74 | outer_list = ['we', 'like', 'proper', 'English'] 75 | 76 | print 'before, outer_list =', outer_list 77 | try_to_change_list_reference(outer_list) 78 | print 'after, outer_list =', outer_list 79 | ``` 80 | 81 | 输出: 82 | 83 | ```python 84 | before, outer_list = ['we', 'like', 'proper', 'English'] 85 | got ['we', 'like', 'proper', 'English'] 86 | set to ['and', 'we', 'can', 'not', 'lie'] 87 | after, outer_list = ['we', 'like', 'proper', 'English'] 88 | ``` 89 | 90 | 既然`the_list`参数是通过值进行传递的,那么为它赋值将会对方法以外没有影响.`the_list`是`outer_list`引用(注意,名词)的一个拷贝,我们将`the_list`指向一个新的列表,但是并没有改变`outer_list`的指向. 91 | 92 | ### 字符串-不可变类型 93 | 94 | **它是不可变类型,所以我们不能改变字符串里的内容.** 95 | 96 | 现在,让我们试着改变引用 97 | 98 | ```python 99 | def try_to_change_string_reference(the_string): 100 | print 'got', the_string 101 | the_string = 'In a kingdom by the sea' 102 | print 'set to', the_string 103 | 104 | outer_string = 'It was many and many a year ago' 105 | 106 | print 'before, outer_string =', outer_string 107 | try_to_change_string_reference(outer_string) 108 | print 'after, outer_string =', outer_string 109 | ``` 110 | 111 | 输出: 112 | 113 | ```python 114 | before, outer_string = It was many and many a year ago 115 | got It was many and many a year ago 116 | set to In a kingdom by the sea 117 | after, outer_string = It was many and many a year ago 118 | ``` 119 | 120 | 又一次,既然`the_string`参数用值进行传递,对它进行赋值并不能改变方法外的值.`the_string`只是`outer_string`引用(名词)的副本,所以我们让`the_string`指向一个新字符串,依然无法改变`outer_string`的指向. 121 | 122 | 希望你清楚以上那些. 123 | 124 | 修改:到现在位置还没有回答"有什么方法同过引用传递变量?",让我们往下看. 125 | 126 | ### 我们该怎么办? 127 | 128 | 你可以返回一个新值.这不会改变传过来的值,但是能得到你想要的结果. 129 | 130 | ```python 131 | def return_a_whole_new_string(the_string): 132 | new_string = something_to_do_with_the_old_string(the_string) 133 | return new_string 134 | 135 | # 你可以像这样调用 136 | my_string = return_a_whole_new_string(my_string) 137 | ``` 138 | 139 | 如果你真的不想用一个返回值,你可以建一个存放你的值的类,然后把它传递给函数或者用一个已有的类,像列表: 140 | 141 | ```python 142 | def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change): 143 | new_string = something_to_do_with_the_old_string(stuff_to_change[0]) 144 | stuff_to_change[0] = new_string 145 | 146 | # 你可以像这样调用 147 | wrapper = [my_string] 148 | use_a_wrapper_to_simulate_pass_by_reference(wrapper) 149 | 150 | do_something_with(wrapper[0]) 151 | ``` 152 | 153 | 虽然看起来有一点笨重,但还是达到你的效果了. -------------------------------------------------------------------------------- /part/29.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |29|2631|158732|31| [url](http://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) | 5 | *** 6 | 7 | ## Python中的"小震撼":变化的默认参数 8 | 9 | 许多 Python 老手也被下面的问题困扰: 10 | 11 | ```python 12 | def foo(a=[]): 13 | a.append(5) 14 | return a 15 | ``` 16 | 17 | Python 新手估计可能会想这个函数返回一个只有元素`[5]`的列表.但是结果却出人意料: 18 | 19 | ```python 20 | >>> foo() 21 | [5] 22 | >>> foo() 23 | [5, 5] 24 | >>> foo() 25 | [5, 5, 5] 26 | >>> foo() 27 | [5, 5, 5, 5] 28 | >>> foo() 29 | ``` 30 | 31 | 我的一个经理曾经碰到过这个特性并把它叫做语言的"动态设计缺陷". 这个现象应当有更深层次的解释, 如果你不懂它的内部它确实非常令人困惑. 然而我不能回答下面的问题:是什么原因使默认参数在函数的定义时被绑定,而不是在执行时?我怀疑这个特性在现实中有没有实际的用途(就像在C语言中有谁去用静态变量?) 32 | 33 | *** 34 | 35 | 事实上这并不是设计缺陷,也不是什么内部或性能原因. 36 | 37 | 原因很简单,Python中的函数是最高等级的对象,而不仅仅是一小段代码. 38 | 39 | 试着这么来理解:**一个函数是一个被它自己定义而执行的对象;默认参数是一种"成员数据",所以它们的状态和其他对象一样,会随着每一次调用而改变.** 40 | 41 | Effbot在它的[Python中的默认参数](http://effbot.org/zone/default-values.htm)对这种行为的原因解释的非常清楚!我强烈建议你读一读能对函数对象的工作原理有更深一步的了解. 42 | 43 | 44 | 45 | 46 | ## Python 中的默认参数(文章翻译) 47 | 48 | Python 默认参数很容易让新手犯错. 49 | 50 | 引起错误的原因通常是使用可变(mutable)对象作为了参数的默认值, 这个可变对象是可以被修改的, 比如说列表(list)和字典(dict) 51 | 52 | 例如: 53 | ```python 54 | >>> def function(data=[]): 55 | ... data.append(1) 56 | ... return data 57 | ... 58 | >>> function() 59 | [1] 60 | >>> function() 61 | [1, 1] 62 | >>> function() 63 | [1, 1, 1] 64 | ``` 65 | 66 | 可以看到上面的列表(list)越来越长, 如果检查这个列表的id, 会发现他返回的是同一个值: 67 | 68 | ```python 69 | >>> id(function()) 70 | 12516768 71 | >>> id(function()) 72 | 12516768 73 | >>> id(function()) 74 | 12516768 75 | ``` 76 | 77 | 原因很简单: 在每次函数调用的时候都使用同一个对象(object), 这个可修改的特性我们叫做 "sticky". 78 | 79 | ### 原理 80 | 81 | 只有当"def"语句执行的时候才会对默认参数值进行赋值, 可以看看文档的定义: 82 | 83 | https://docs.python.org/2.0/ref/function.html 84 | 85 | 还要注意的是在Python 中 "def" 是可执行语句, 默认参数仅在"def" 语句环境里生效.每次执行"def"语句都会创建一个新的函数对象(每次都会对默认参数进行赋值) 86 | -------------------------------------------------------------------------------- /part/3.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |3|6154|1947774|26| [url](http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) | 5 | *** 6 | 7 | ## 在Python中有三元运算符吗? 8 | 9 | 如果没有,可以像其他语言用的简单方法来实现吗? 10 | 11 | *** 12 | 13 | 有,在2.5版本中加入.对于python初学者可能有点难以理解,所以要记住了. 14 | 15 | 语法如下: 16 | 17 | ```python 18 | a if test else b 19 | ``` 20 | 21 | 根据`test`的布尔值来判断返回的是`a`还是`b`;如果`test`为真则返回`a`,反之则返回`b`. 22 | 23 | 来个大栗子: 24 | 25 | ```python 26 | >>> 'true' if True else 'false' 27 | 'true' 28 | >>> 'true' if False else 'false' 29 | 'false' 30 | ``` 31 | 32 | 官方文档: 33 | * [Conditional expressions](https://docs.python.org/3/reference/expressions.html#conditional-expressions) 34 | * [Is there an equivalent of C’s ”?:” ternary operator?](https://docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator) 35 | 36 | 37 | -------------------------------------------------------------------------------- /part/30.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |30|2616|1726238|22| [url](http://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent) | 5 | *** 6 | 7 | ## 如何克隆或者 copy 一个 list ? 8 | 9 | 使用 `new_list = my_list` 来 copy list , 但是 每次 `my_list` 改变 `new_list` 都会跟着改变. 10 | 11 | 这是为什么? 12 | 13 | *** 14 | 15 | 用 `new_list = my_list` 来进行 copy 实际上并没有得到两个 list.这个语句并不是真正的复制了一个 list,而是复制了一个 list 的引用, 所以 `my_list` 和 `new_list` 最终指向了同一个 list. 16 | 17 | 为了真正 copy 一个 list, 你可以用下面几种方法: 18 | 19 | * 你可以使用内建函数 `list.copy()` 方法(从 Python3.3 以上可以使用): 20 | ```python 21 | new_list = old_list.copy() 22 | ``` 23 | 24 | * 也可以使用切片: 25 | ```python 26 | new_list = old_list[:] 27 | ``` 28 | [Alex Martelli's](https://en.wikipedia.org/wiki/Alex_Martelli)早在[2007](https://www.youtube.com/watch?v=g7V89K8QfgQ)指出这个切边的语法很奇怪, 他主张用下一个方法可读性更强. 29 | 30 | * 使用内建的 `list()` 函数: 31 | ```python 32 | new_list = list(old_list) 33 | ``` 34 | 35 | * 还可以使用 `copy.copy()`: 36 | ```python 37 | import copy 38 | new_list = copy.copy(old_list) 39 | ``` 40 | 它比 `list()` 方法更慢, 因为它需要先找出 `old_list` 的数据类型. 41 | 42 | * 如果 list 中包含对象并且你也希望 copy 这些对象, 那么可以使用 `copy.deepcopy()`: 43 | ```python 44 | import copy 45 | new_list = copy.deepcopy(old_list) 46 | ``` 47 | 显然这种方法更加慢, 并且需要更多的内存, 但是有些时候不可避免需要用到它. 48 | 49 | 例如: 50 | 51 | ```python 52 | import copy 53 | 54 | class Foo(object): 55 | def __init__(self, val): 56 | self.val = val 57 | 58 | def __repr__(self): 59 | return str(self.val) 60 | 61 | foo = Foo(1) 62 | 63 | a = ['foo', foo] 64 | b = a.copy() 65 | c = a[:] 66 | d = list(a) 67 | e = copy.copy(a) 68 | f = copy.deepcopy(a) 69 | 70 | # edit orignal list and instance 71 | a.append('baz') 72 | foo.val = 5 73 | 74 | print('original: %r\n list.copy(): %r\n slice: %r\n list(): %r\n copy: %r\n deepcopy: %r' 75 | % (a, b, c, d, e, f)) 76 | ``` 77 | 78 | 结果: 79 | 80 | ```python 81 | original: ['foo', 5, 'baz'] 82 | list.copy(): ['foo', 5] 83 | slice: ['foo', 5] 84 | list(): ['foo', 5] 85 | copy: ['foo', 5] 86 | deepcopy: ['foo', 1] 87 | ``` -------------------------------------------------------------------------------- /part/31.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |31|2598|2628372|24| [url](http://stackoverflow.com/questions/1720421/how-do-i-concatenate-two-lists-in-python) | 5 | *** 6 | 7 | ## 合并两个列表 8 | 9 | 怎样合并两个列表? 10 | 11 | 例如: 12 | 13 | ```python 14 | listone = [1,2,3] 15 | listtwo = [4,5,6] 16 | ``` 17 | 18 | 我期待: 19 | 20 | ```python 21 | mergedlist == [1, 2, 3, 4, 5, 6] 22 | ``` 23 | 24 | *** 25 | 26 | 在Python中非常容易. 27 | 28 | ```python 29 | mergedlist = listone + listtwo 30 | ``` -------------------------------------------------------------------------------- /part/32.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |32|2573|1723365|7| [url](http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods) | 5 | *** 6 | 7 | ## 理解Python中`super()`和`__init__()`方法 8 | 9 | 我试着理解`super()`方法.从表面上看,两个子类实现的功能都一样.我想问它们俩的区别在哪里? 10 | 11 | ```python 12 | class Base(object): 13 | def __init__(self): 14 | print "Base created" 15 | 16 | class ChildA(Base): 17 | def __init__(self): 18 | Base.__init__(self) 19 | 20 | class ChildB(Base): 21 | def __init__(self): 22 | super(ChildB, self).__init__() 23 | 24 | print ChildA(),ChildB() 25 | ``` 26 | 27 | *** 28 | 29 | 30 | `super()`的好处就是可以避免直接使用父类的名字.但是它主要用于多重继承,[这里面](http://www.artima.com/weblogs/viewpost.jsp?thread=236275)有很多好玩的东西.如果还不了解的话可以看看[官方文档](https://docs.python.org/2/library/functions.html#super) 31 | 32 | 注意在Python3.0里语法有所改变:你可以用`super().__init__()`替换`super(ChildB, self).__init__()`.(在我看来非常nice) -------------------------------------------------------------------------------- /part/33.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |33|2565|2031233|16| [url](http://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python) | 5 | *** 6 | 7 | ## 复制文件 8 | 9 | 怎么在Python里赋值文件?在`os`下没找到复制的方法. 10 | 11 | [`shutil`](http://docs.python.org/2/library/shutil.html)有许多的方法.其中之一就是: 12 | 13 | ```python 14 | copyfile(src, dst) 15 | ``` 16 | 17 | 把`src`文件的内容复制给`dst`.目的地址必须是可写的;否则将会出现`IOError`错误.如果`dst`已经存在,将会被覆盖.一些像字符或者块设备不能用这个方法赋值.`src`和`dst`是路径名的字符串形式. -------------------------------------------------------------------------------- /part/34.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |34|2554|3044670|38| [url](http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows) | 5 | *** 6 | 7 | ## 怎么在windows下安装pip? 8 | 9 | 怎么在windows下安装pip? 10 | 11 | *** 12 | 13 | ### Python3.4+ 14 | 15 | 好消息,Python3.4已经自带Pip.这是所有Python发行版中最好的特性了.方便了所有人使用公共库.新手再也不用操心安装额外库的繁琐步骤了.它自带的包管理器中加入了 Ruby, Nodejs, Haskell, Perl, Go等其他几乎所有的开源社区流行语言.谢谢Python. 16 | 17 | 当然,这并不意味着所有的Python包问题已经解决.在一段时间看来仍然不乐观.我在[Python有包管理系统吗?](http://stackoverflow.com/questions/2436731/does-python-have-a-package-module-management-system/13445719#13445719)也讨论过这个问题. 18 | 19 | 同样对于Python2.x用户(几乎一般人),还没有计划在Python中自带Pip. 20 | 只能自己动手了. 21 | 22 | ### Python 2.x 和 Python ≤ 3.3 23 | 24 | 尽管Python吹的`简单易用`的哲学,但是Python不提供包管理工具.更糟糕的是,Pip直到现在还是非常的难以安装. 25 | 26 | #### 官方指南 27 | 28 | 在 http://www.pip-installer.org/en/latest/installing.html 下载`get-pip.py`,把它保存下来注意不要把`.py`后缀改成`.txt`. 29 | 然后在命令提示符上输入: 30 | 31 | ``` 32 | python get-pip.py 33 | ``` 34 | 35 | 你可能还需要管理员权限来执行它.跟着做 http://technet.microsoft.com/en-us/library/cc947813(v=ws.10).aspx 36 | 37 | #### 另一种方法 38 | 39 | 官方文档告诉我们安装Pip和各种依赖的源.对有经验的人来说太麻烦了,对于新手又有点难. 40 | 41 | Christoph Gohlke已经为我们做好了下载Python包的安装器(.msi).它可以为的Python版本建立依赖,不管32bit还是64bit.你只需要: 42 | 43 | * 安装setuptools http://www.lfd.uci.edu/~gohlke/pythonlibs/#setuptools 44 | * 安装pip http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip 45 | 46 | 在我这,Pip安装到了`C:\Python27\Scripts\pip.exe`.在你的电脑上找到`pip.exe`,然后把文件夹(eg.`C:\Python27\Scripts`)添加你的路径(编辑你的环境变量).现在你应当可以在命令行中运行pip了.试试安装一个包: 47 | 48 | ``` 49 | pip install httpie 50 | ``` 51 | 52 | 终于可以运行了!下面是一些问题的解决办法 53 | 54 | #### 代理问题 55 | 56 | 如果你在办公环境,那么你有可能有一个HTTP代理.把环境变量设置成[`http_proxy`和`https_proxy`](https://docs.python.org/2/library/urllib.html).大多数应用程序都管用(包括免费软件).语法如下: 57 | 58 | ``` 59 | http://proxy_url:port 60 | http://username:password@proxy_url:port 61 | ``` 62 | 63 | 如果你不幸用的是微软的NTLM代理.那就没救了.唯一的办法就是安装一个友好的代理吧. http://cntlm.sourceforge.net/ 64 | 65 | #### 找不到vcvarsall.bat 66 | 67 | Python有的模块是用C或C++写的.Pip尝试从源码编译.如果你没有安装或设置过C/C++编译器,你将会看到下面的错误: 68 | 69 | ``` 70 | Error: Unable to find vcvarsall.bat 71 | ``` 72 | 73 | 你可以通过像MinGw或者Visual C++这样的[C++编译器](http://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat)来解决此问题.微软实际上已经自带了一个为Python准备的编译器,或者试试 http://aka.ms/vcpython27 74 | 75 | 可以这个Christoph的网站来查看安装包 http://www.lfd.uci.edu/~gohlke/pythonlibs/ 76 | -------------------------------------------------------------------------------- /part/35.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |35|2414|741311|22| [url](http://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) | 5 | *** 6 | 7 | ## Python中`**`和`*`参数有什么用? 8 | 9 | 见55 -------------------------------------------------------------------------------- /part/36.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |36|2411|2586996|19| [url](http://stackoverflow.com/questions/606191/convert-bytes-to-a-string) | 5 | *** 6 | 7 | ## bytes 换成 string 8 | 9 | 我通过这个代码来获取外部程序的输出: 10 | 11 | ```python 12 | >>> from subprocess import * 13 | >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] 14 | ``` 15 | 16 | communicate() 方法返回一个字节数组: 17 | 18 | ```python 19 | >>> command_stdout 20 | b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' 21 | ``` 22 | 23 | 但是我想让它输出成 Python string. 像这样: 24 | 25 | ```python 26 | >>> print(command_stdout) 27 | -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 28 | -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 29 | ``` 30 | 31 | 我试着用 [`binascii.b2a_qp()`](http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp) 方法但是如下: 32 | 33 | ```python 34 | >>> binascii.b2a_qp(command_stdout) 35 | b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' 36 | ``` 37 | 38 | 谁知道怎么讲字节转换成 string ? 39 | 40 | *** 41 | 42 | 你需要 decode 字节对象来产生 string: 43 | 44 | ```python 45 | >>> b"abcde" 46 | b'abcde' 47 | 48 | # utf-8 is used here because it is a very common encoding, but you 49 | # need to use the encoding your data is actually in. 50 | >>> b"abcde".decode("utf-8") 51 | 'abcde' 52 | ``` -------------------------------------------------------------------------------- /part/37.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |37|2408|1215558|12| [url](http://stackoverflow.com/questions/448271/what-is-init-py-for) | 5 | *** 6 | 7 | ## `__init__.py` 的作用 8 | 9 | *** 10 | 11 | 它是作为包的一部分. [文档](http://docs.python.org/tutorial/modules.html#packages) 12 | 13 | > `__init__.py` 作为标识 Python 包的文件, 这么做是为了防止 Python 在引入 module 时误引入其他类似 `string` 这样的通用名.`__init__.py` 最简单的方式是空文件, 但是它可以为包执行初始化代码或者设置 `__all__` 变量 14 | -------------------------------------------------------------------------------- /part/38.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |38|2327|978966|64| [url](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) | 5 | *** 6 | 7 | ## 在Python怎么样才能把列表分割成同样大小的块? 8 | 9 | 我有一个任意长度的列表,我需要把它们切成相同大小并且使用它们.有一些简单的方法,比如设置一个计数器和两个列表,当第二个列表装满后,把它存进第一个列表然后让第二个列表变空一遍存放下一轮的数据,但是这么做代价太大了. 10 | 11 | 我想是不是还有其他更好的方法,比如生成器 12 | 13 | 像下面这样: 14 | 15 | ```python 16 | l = range(1, 1000) 17 | print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] 18 | ``` 19 | 20 | 我试着在`itertools`找一些有用的方法,但是还没有找到.也可能是我还没有看到. 21 | 22 | 相似问题:[What is the most “pythonic” way to iterate over a list in chunks?]() 23 | 24 | *** 25 | 26 | 下面是生成器方法: 27 | 28 | ```python 29 | def chunks(l, n): 30 | """ Yield successive n-sized chunks from l. 31 | """ 32 | for i in xrange(0, len(l), n): 33 | yield l[i:i+n] 34 | ``` 35 | 36 | ```python 37 | import pprint 38 | pprint.pprint(list(chunks(range(10, 75), 10))) 39 | [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], 40 | [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], 41 | [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], 42 | [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], 43 | [50, 51, 52, 53, 54, 55, 56, 57, 58, 59], 44 | [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], 45 | [70, 71, 72, 73, 74]] 46 | ``` 47 | 48 | *** 49 | 50 | 一句话 51 | 52 | ```python 53 | tuple(l[i:i+n] for i in xrange(0, len(l), n)) 54 | ``` -------------------------------------------------------------------------------- /part/39.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |39|2323|1804194|8| [url](http://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python) | 5 | *** 6 | 7 | ## 手动抛出异常 8 | 9 | 我想故意制造一个错误,所以我可以转到`excepy:`语句 10 | 11 | 我怎么做? 12 | 13 | *** 14 | 15 | 不能在Pythonic了; 16 | 17 | ```python 18 | raise Exception("I know python!") 19 | ``` 20 | 21 | 想得到更多信息,看[这里](http://docs.python.org/reference/simple_stmts.html#the-raise-statement) -------------------------------------------------------------------------------- /part/40.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |40|2284|3966336|28| [url](http://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int) | 5 | *** 6 | 7 | ## 把字符串解析成浮点数或者整数 8 | 9 | 在Python里,怎么样把一个数字型字符串像`"545.2222"`解析成对应的浮点值`545.2222`?或者把一个`"31"`解析成`31`? 10 | 11 | 我只是想知道怎么样才能解析一个浮点型字符串编程浮点数,或者整型字符串转换成整型? 12 | 13 | *** 14 | 15 | ```python 16 | >>> a = "545.2222" 17 | >>> float(a) 18 | 545.22220000000004 19 | >>> int(float(a)) 20 | 545 21 | ``` -------------------------------------------------------------------------------- /part/41.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |41|2257|3097215|13| [url](http://stackoverflow.com/questions/5137497/find-current-directory-and-files-directory) | 5 | *** 6 | 7 | ## 查找当前目录和文件目录 8 | 9 | 在 Python 中什么命令可以找到: 10 | 11 | 1. 当前目录(在终端中运行的 Python 脚本) 12 | 2. 我执行的文件在哪里? 13 | 14 | *** 15 | 16 | 可以通过下面的命令获得执行的 Python 文件所在的位置: 17 | 18 | ```python 19 | import os 20 | dir_path = os.path.dirname(os.path.realpath(__file__)) 21 | ``` 22 | 23 | (注意当你已经使用 `os.chdir()` 来该改变当前工作目录的话, 上面得到的结果并不准确, 因为 `__file__` 变量只表示当前工作目录的相对位置, 不会被 `os.chdir()` 所改变) 24 | 25 | 获取当前工作目录: 26 | 27 | ```python 28 | import os 29 | cwd = os.getcwd() 30 | ``` 31 | 32 | 下面是几个函数,模块或者变量的文档: 33 | 34 | * [`os`](https://docs.python.org/library/os.html) 和 [`os.path`](https://docs.python.org/library/os.path.html#module-os.path) 模块. 35 | * [`__file__`](https://docs.python.org/reference/datamodel.html) 变量 36 | * [`os.path.realpath(path)`](https://docs.python.org/library/os.path.html#os.path.realpath) 37 | * [`os.path.dirname(path)`](https://docs.python.org/library/os.path.html#os.path.dirname) 38 | * [`os.getcwd()`](https://docs.python.org/library/os.html#os.getcwd) 39 | * [`os.chdir(path)`](https://docs.python.org/library/os.html#os.chdir) -------------------------------------------------------------------------------- /part/42.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |42|2215|3027686|20| [url](http://stackoverflow.com/questions/466345/converting-string-into-datetime) | 5 | *** 6 | 7 | ## 把字符串转化成时间 8 | 9 | 短小精悍.我有一个特别大的列表存储了下面的字符串: 10 | 11 | ```python 12 | Jun 1 2005 1:33PM 13 | Aug 28 1999 12:00AM 14 | ``` 15 | 16 | 我想把它们转化成合适的时间格式存进数据库,所以我需要把它们变成真正的时间对象. 17 | 18 | 非常感谢帮助. 19 | 20 | *** 21 | 22 | 检查[time](http://docs.python.org/2/library/time.html)模块的[strptime](http://docs.python.org/2/library/time.html#time.strptime)函数.它是[strftime](http://docs.python.org/2/library/time.html#time.strftime)的转换. 23 | 24 | *** 25 | 26 | ```python 27 | from datetime import datetime 28 | 29 | date_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p') 30 | ``` -------------------------------------------------------------------------------- /part/43.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |43|2199|2049948|13| [url](http://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder) | 5 | *** 6 | 7 | ## 删除文件或者文件夹 8 | 9 | *** 10 | 11 | [`os.remove()`](http://docs.python.org/library/os.html#os.remove) 删除文件 12 | [`os.rmdir()`](http://docs.python.org/library/os.html#os.rmdir) 删除空文件夹 13 | [`shutil.rmtree()`](http://docs.python.org/library/shutil.html#shutil.rmtree) 删除文件夹和里面的内容 14 | [`pathlib.Path.unlink()`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.unlink) 删除文件或链接 15 | [`pathlib.Path.rmdir()`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.unlink) 删除空文件夹 16 | -------------------------------------------------------------------------------- /part/44.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |44|2195|1299936|45| [url](http://stackoverflow.com/questions/287871/how-to-print-colored-text-in-python) | 5 | *** 6 | 7 | ## 怎么在终端里输出颜色? 8 | 9 | 怎么样用Python在终端里输出带颜色的文本?最好的代替块字符的unicode字符是什么?(What is the best Unicode symbol to represent a solid block?这句话没理解) 10 | 11 | *** 12 | 13 | 这依赖于你用哪种操作系统.最常用的方法就是输出ANSI转义序列.例如,下面的: 14 | 15 | ```python 16 | class bcolors: 17 | HEADER = '\033[95m' 18 | OKBLUE = '\033[94m' 19 | OKGREEN = '\033[92m' 20 | WARNING = '\033[93m' 21 | FAIL = '\033[91m' 22 | ENDC = '\033[0m' 23 | ``` 24 | 25 | 可以这么用上面的代码: 26 | 27 | ```python 28 | print bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC 29 | ``` 30 | 31 | 这种方法适合OS X,linux和windows系统.还有一些其他的ansi代码可以设置颜色,消除光标或者其他. 32 | 33 | 如果想要应用更复杂的功能(听起来像是如果你正在写一个游戏),你应该看看"curses"模块,它包含了许多关于次部分复杂操作.[Python Curses HowTO](https://docs.python.org/2/howto/curses.html)可以作为好的介绍. 34 | 35 | 如果你不使用拓展的ASCII(比如不是一个PC),`#`或者`@`可能是你最好的选择.如果你用的是[IBM扩展ascii字符设置](http://telecom.tbi.net/asc-ibm.html),你还可以有更多的选择.176,177,178和219是"块字符" 36 | 37 | 一些现代的基于文本的程序,像"Swarf Fortress",显示的文本使用图像模式,而用的字体也是传统的计算机字体的图像.你可以在[Dwarf Fortress Wiki](http://dwarffortresswiki.org/DF2014:Tilesets)找到你可以用的字符. 38 | 39 | [Text Mode Demo Contest ](http://en.wikipedia.org/wiki/Text_Mode_Demo_Contest)也有许多资料可供参考. 40 | 41 | 我想可能有点跑题了.我在设计一个史诗级别的基于文本的冒险游戏.祝你好运! 42 | 43 | *** 44 | 45 | 怎么就没人提[Python termcolor module](https://pypi.python.org/pypi/termcolor).用法相当简单: 46 | 47 | ```python 48 | from termcolor import colored 49 | 50 | print colored('hello', 'red'), colored('world', 'green') 51 | ``` 52 | 53 | 虽然有点简单,但是对于游戏程序和你想要的"colored blocks"来说足够了. -------------------------------------------------------------------------------- /part/45.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |45|2191|3006128|14| [url](http://stackoverflow.com/questions/663171/how-do-i-get-a-substring-of-a-string-in-python) | 5 | *** 6 | 7 | ## 获得一个字符串的子串 8 | 9 | 有什么方法获得一个字符串的字串,比如从一个字符串的第三个字符到最后. 10 | 11 | 可能是`myString[2:end]`? 12 | 13 | *** 14 | 15 | ```python 16 | >>> x = "Hello World!" 17 | >>> x[2:] 18 | 'llo World!' 19 | >>> x[:2] 20 | 'He' 21 | >>> x[:-2] 22 | 'Hello Worl' 23 | >>> x[-2:] 24 | 'd!' 25 | >>> x[2:-2] 26 | 'llo Worl' 27 | ``` 28 | 29 | 上面的概念在Python中叫"slicing"(切片),不止在字符串上有这个方法.在[这里](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation)有详细的解释. -------------------------------------------------------------------------------- /part/46.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |46|2177|1871474|11| [url](http://stackoverflow.com/questions/4906977/how-to-access-environment-variable-values) | 5 | *** 6 | 7 | ## 在 Python 中如何获取环境变量 8 | 9 | *** 10 | 11 | 环境变量可以通过 [`os.environ`](https://docs.python.org/library/os.html#os.environ) 来获取 12 | 13 | ```python 14 | import os 15 | print(os.environ['HOME']) 16 | ``` 17 | 18 | 或者你可以查看一下所有环境变量的列表: 19 | 20 | ```python 21 | os.environ 22 | ``` 23 | 24 | ```python 25 | # using get will return `None` if a key is not present rather than raise a `KeyError` 26 | print(os.environ.get('KEY_THAT_MI¡GHT_EXIST')) 27 | 28 | # os.getenv is equivalent, and can also give a default value instead of `None` 29 | print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value)) 30 | ``` 31 | 32 | [`Python default installation`](https://docs.python.org/install/index.html#how-installation-works) 在 Windows 中是 `C:\Python`, 如果你想在运行时得到可以运行下面的: 33 | 34 | ```python 35 | import sys 36 | print(sys.prefix) 37 | ``` -------------------------------------------------------------------------------- /part/47.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |47|2165|206370|10| [url](http://stackoverflow.com/questions/30081275/why-is-1000000000000000-in-range1000000000000001-so-fast-in-python-3) | 5 | *** 6 | 7 | ## 为什么 "1000000000000000 in range(1000000000000001)" 在 Python3 里速度那么快? 8 | 9 | 在我理解 `range()` 函数作为 [an object type in Python 3](https://docs.python.org/3/library/stdtypes.html#typesseq-range) 生成的内容和生成器差不多快. 10 | 11 | 我测试如下语句 12 | 13 | ```python 14 | 1000000000000000 in range(1000000000000001) 15 | ``` 16 | 17 | 不管我加了多少个 0 这个计算的结果时间都差不多 18 | 19 | 我还试了下这个, 结果差不多, 非常快: 20 | 21 | ```python 22 | 000000000000000000000 in range(0,1000000000000000000001,10) # count by tens 23 | ``` 24 | 25 | 但是我自己写了个代码速度就非常慢: 26 | 27 | ```python 28 | def my_crappy_range(N): 29 | i = 0 30 | while i < N: 31 | yield i 32 | i += 1 33 | return 34 | ``` 35 | 36 | 所以我想问为啥 `range()` 如此之快? 37 | 38 | *** 39 | 40 | Python3 的 `range()` 对象并不会立即产生数值;它会在需要时来产生.它包含你的起始, 终止和步长, 它会随着每次迭代来产生下一个数值. 41 | 42 | 这个对象通过 [`object.__contains__ hook`](https://docs.python.org/3/reference/datamodel.html#object.__contains__) 来实现的.计算的时间复杂度为 `O(1)`.在迭代的过程中其实是不需要一下计算出所有的数值的. 43 | 44 | 根据 [`range()`](https://docs.python.org/3/library/stdtypes.html#range) 文档 45 | 46 | > `range` 优于于 `list` 和 `tuple` 的地方在于不管它的范围是多少它只占用少量的内存(因为它只保存 `start`, `stop`, `step`, 按需得到数值) 47 | 48 | 所以你可以这么写你的 `range()`: 49 | 50 | ```python 51 | class my_range(object): 52 | def __init__(self, start, stop=None, step=1): 53 | if stop is None: 54 | start, stop = 0, start 55 | self.start, self.stop, self.step = start, stop, step 56 | if step < 0: 57 | lo, hi = stop, start 58 | else: 59 | lo, hi = start, stop 60 | self.length = ((hi - lo - 1) // abs(step)) + 1 61 | 62 | def __iter__(self): 63 | current = self.start 64 | if self.step < 0: 65 | while current > self.stop: 66 | yield current 67 | current += self.step 68 | else: 69 | while current < self.stop: 70 | yield current 71 | current += self.step 72 | 73 | def __len__(self): 74 | return self.length 75 | 76 | def __getitem__(self, i): 77 | if i < 0: 78 | i += self.length 79 | if 0 <= i < self.length: 80 | return self.start + i * self.step 81 | raise IndexError('Index out of range: {}'.format(i)) 82 | 83 | def __contains__(self, num): 84 | if self.step < 0: 85 | if not (self.stop < num <= self.start): 86 | return False 87 | else: 88 | if not (self.start <= num < self.stop): 89 | return False 90 | return (num - self.start) % self.step == 0 91 | ``` 92 | 93 | 这个代码和真正的 `range()` 缺少了像 `.index()`, `.count()` 方法,但是应当可以给你些启发. 94 | 95 | -------------------------------------------------------------------------------- /part/48.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |48|2132|2911412|17| [url](http://stackoverflow.com/questions/332289/how-do-you-change-the-size-of-figures-drawn-with-matplotlib) | 5 | *** 6 | 7 | ## 如何改变 matplotlib 图像大小 8 | 9 | *** 10 | 11 | [figure](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.figure.html#matplotlib.pyplot.figure)告诉你如何操作: 12 | 13 | ```python 14 | from matplotlib.pyplot import figure 15 | figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k') 16 | ``` 17 | 18 | `figure(figsize=(1,1))` 可以创建一个 1x1 英寸的图像, 由 80x80 像素组成,如果想改变像素,可以改变 dpi 大小. -------------------------------------------------------------------------------- /part/49.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |49|2121|2187007|12| [url](http://stackoverflow.com/questions/930397/getting-the-last-element-of-a-list) | 5 | *** 6 | 7 | ## 获取列表最后一个元素 8 | 9 | 在Python里,如何获取一个列表的最后一个元素? 10 | 11 | *** 12 | 13 | `some_list[-1]`最短最Pythonic的方法. 14 | 15 | 事实上你可以用这个语法做好多事.`some_list[-n]`语法获取倒数第n个元素.所以`some_list[-1]`获取最后一个元素,`some_list[-2]`获取倒数第二个,等等.最后`some_list[-len(some_list)]`可以获取第一个元素~~ 16 | 17 | 你也可以用这种方法获取列表元素,例如: 18 | 19 | ```python 20 | >>> some_list = [1, 2, 3] 21 | >>> some_list[-1] = 5 # Set the last element 22 | >>> some_list[-2] = 3 # Set the second to last element 23 | >>> some_list 24 | [1, 3, 5] 25 | ``` -------------------------------------------------------------------------------- /part/5.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |5|5697|3946153|39| [url](http://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions) | 5 | *** 6 | 7 | ## 用Python如何一个文件是否存在? 8 | 9 | 不用`try:`语句可以一个文件存在 10 | 11 | *** 12 | 13 | 如果不确定文件存不存在,可以这样做: 14 | 15 | ```python 16 | import os.path 17 | os.path.isfile(fname) 18 | ``` 19 | 20 | -------------------------------------------------------------------------------- /part/50.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |50|2096|1246185|55| [url](http://stackoverflow.com/questions/2720014/how-to-upgrade-all-python-packages-with-pip) | 5 | *** 6 | 7 | ## 用pip升级所有包 8 | 9 | 可不可以用pip一次性升级所有的Python包? 10 | 11 | 注:在官方的issue里也有这个[需求](http://stackoverflow.com/questions/2720014/upgrading-all-packages-with-pip). 12 | 13 | *** 14 | 15 | 内部还不支持这个命令,但是可以这样: 16 | 17 | ``` 18 | pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs pip install -U 19 | ``` -------------------------------------------------------------------------------- /part/51.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |51|2092|632450|23| [url](http://stackoverflow.com/questions/101754/is-there-a-way-to-run-python-on-android) | 5 | *** 6 | 7 | ## 有方法让Python运行在Android上吗? 8 | 9 | 我喜欢Android平台.试试上我和几个朋友在Spoxt项目里在用ADC(数模转换器?) 10 | 11 | 但是我一点也不喜欢Java.我们工作在S60版本而且一个不错的Python的API.我知道Android上没有官方的Python版本,但是既然有Jython,有没有什么方法让它们能在Android上工作? 12 | 13 | *** 14 | 15 | 有一种方法,使用[Kivy](http://kivy.org/): 16 | 17 | ``` 18 | 交互界面快速开发应用的Python开源库,像多点触控app. 19 | ``` 20 | 21 | ``` 22 | Kivy运行在 Linux, Windows, OS X, Android and iOS.你也可以在所有的平台上运行Python代码 23 | ``` 24 | 25 | [Kivy的应用](https://play.google.com/store/apps/details?id=org.kivy.showcase) 26 | 27 | -------------------------------------------------------------------------------- /part/52.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |52|2091|2439201|5| [url](http://stackoverflow.com/questions/6797984/how-do-i-lowercase-a-string-in-python) | 5 | *** 6 | 7 | ## 在 Python 中如何将字符串转回为小写 8 | 9 | *** 10 | 11 | ```Python 12 | s = "Kilometer" 13 | print(s.lower()) 14 | ``` 15 | 16 | 官方文档 [`str.lower`](https://docs.python.org/3.4/library/stdtypes.html?highlight=str.lower#str.lower) -------------------------------------------------------------------------------- /part/53.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |53|2090|2734719|22| [url](http://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas) | 5 | -------------------------------------------------------------------------------- /part/54.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |54|2069|2976076|10| [url](http://stackoverflow.com/questions/17071871/how-to-select-rows-from-a-dataframe-based-on-column-values) | 5 | -------------------------------------------------------------------------------- /part/55.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |55|2027|3678001|28| [url](http://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) | 5 | *** 6 | 7 | ## 把文件一行行读入数组 8 | 9 | 怎么样才能一行行的读一个文件并把每行作为一个元素存入一个数组? 10 | 11 | 我想读取文件的没一行,然后把每行加入到数组的最后.我没找到这样的方法而且我也没能在Python中找到创建字符数组的方法. 12 | 13 | *** 14 | 15 | ```python 16 | with open(fname) as f: 17 | content = f.readlines() 18 | ``` 19 | 20 | 我想你说的是[list](http://docs.python.org/glossary.html#term-list)而不是数组. -------------------------------------------------------------------------------- /part/56.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |56|1970|1218914|21| [url](http://stackoverflow.com/questions/68645/are-static-class-variables-possible-in-python) | 5 | *** 6 | 7 | ## Python 中类的静态变量 8 | 9 | 在 Python 中如何实现类的静态变量或者方法 10 | 11 | *** 12 | 13 | 在类定义中声明且在方法里未声明的是类的静态变量 14 | 15 | ```python 16 | >>> class MyClass: 17 | ... i = 3 18 | ... 19 | >>> MyClass.i 20 | 3 21 | ``` 22 | 23 | 这样做会生成一个类级别的 `i` 变量, 而不是依赖于某个实例的 `i` 变量, 所以你可以: 24 | 25 | ```python 26 | >>> m = MyClass() 27 | >>> m.i = 4 28 | >>> MyClass.i, m.i 29 | >>> (3, 4) 30 | ``` 31 | 32 | 和 C++ 和 Java 不一样, 这种静态变量不能通过实例来访问有点像 C#. 33 | 34 | 可以看一看 [what the Python tutorial has to say on the subject of classes and class objects](https://docs.python.org/2/tutorial/classes.html#class-objects) 35 | 36 | [static methods](http://web.archive.org/web/20090214211613/http://pyref.infogami.com/staticmethod) 的相关文档 ["Built-in Functions" in the Python Library Reference](https://docs.python.org/2/library/functions.html#staticmethod) 37 | 38 | ```python 39 | class C: 40 | @staticmethod 41 | def f(arg1, arg2, ...): ... 42 | ``` 43 | 44 | 有人提到使用 [classmethod](https://docs.python.org/2/library/functions.html#classmethod) 作为静态方法, 它接受类的类型作为第一个参数, 但是我依然对这种方法的有点疑问, 如果你也是, 那可能没什么关系 -------------------------------------------------------------------------------- /part/57.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |57|1955|3290422|9| [url](http://stackoverflow.com/questions/1712227/how-do-i-get-the-number-of-elements-in-a-list) | 5 | *** 6 | 7 | ## 怎么样获取一个列表的长度? 8 | 9 | ```python 10 | items = [] 11 | items.append("apple") 12 | items.append("orange") 13 | items.append("banana") 14 | 15 | # FAKE METHOD:: 16 | items.amount() # 返回 3 17 | ``` 18 | 19 | 怎么样做才对? 20 | 21 | *** 22 | 23 | [len](https://docs.python.org/2/library/functions.html#len)函数可以用于Python中许多的类型,包括内建类型和标准库类型. 24 | 25 | ```python 26 | >>len([1,2,3]) 27 | 3 28 | ``` -------------------------------------------------------------------------------- /part/58.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |58|1939|764091|18| [url](http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) | 5 | *** 6 | 7 | ## 通过列表中字典的值对列表进行排序 8 | 9 | 我的到了一个字典的列表,我想对字典的值进行排序. 10 | 11 | ```python 12 | [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] 13 | ``` 14 | 15 | 对name进行排序,应当是: 16 | 17 | ```python 18 | [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}] 19 | ``` 20 | 21 | *** 22 | 23 | 用key比用cmp更清晰明了: 24 | 25 | ```python 26 | newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) 27 | ``` 28 | 29 | 或者其他人的建议: 30 | 31 | ```python 32 | from operator import itemgetter 33 | newlist = sorted(list_to_be_sorted, key=itemgetter('name')) 34 | ``` 35 | -------------------------------------------------------------------------------- /part/59.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |59|1894|2898051|27| [url](http://stackoverflow.com/questions/11346283/renaming-columns-in-pandas) | 5 | -------------------------------------------------------------------------------- /part/6.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |6|4963|3468096|61| [url](http://stackoverflow.com/questions/89228/calling-an-external-command-from-python) | 5 | *** 6 | 7 | ## 在Python中调用外部命令? 8 | 9 | 怎么在Python脚本里调用外部命令?(就好像直接输入在Unix shell中或者windows的命令行里) 10 | 11 | *** 12 | 13 | 来来来,我给你叨咕叨咕各种方法和各自优缺点: 14 | 15 | 1. `os.system("命令加参数")`把命令和参数传递给你系统的shell中.用这个命令的好处在于你可以一次运行好多命令还可以设置管道来进行重定向.来个栗子:`os.system("命令 < 出入文件 | 另一个命令 > 输出文件")`尽管它非常方便,但是你还是不得不手动输入像空格这样的sehll字符.从另一方面讲,对于运行简单的shell命令而不去调用外部程序来说的话还是非常好用的. 16 | 2. `stream = os.popen("命令和参数")`这个命令和`os.system`差不多,但是它提供了一个连接标准输入/输出的管道.还有其他3个`popen`可以调用.如果你传递一个字符串,你的命令会把它传递给shell,如果你传递的是一个列表,那么就不用担心溢出字符了(escaping characters). 17 | 3. `subprocess`模块的管道`Popen`.这个`Popen`是打算用来替代`os.popen`的方法,它有点复杂: 18 | 19 | ```python 20 | print subprocess.Popen("echo Hello World", shell=True,stdout=PIPE).stdout.read() 21 | ``` 22 | 23 | 而用`os.popen`: 24 | 25 | ```python 26 | print os.popen("echo Hello World").read() 27 | ``` 28 | 29 | 它最大的优点就是一个类里代替了原来的4个不同的`popen` 30 | 31 | 4. `subprocess`的`call`方法.它的基本用法和上面的`Popen`类参数一致,但是它会等待命令结束后才会返回程序.来个大狸子: 32 | 33 | ```python 34 | return_code = subprocess.call("echo Hello World", shell=True) 35 | ``` 36 | 37 | 5. os模块里也有C语言里`fork/exec/spawn`方法,但是我不建议你直接用它们. 38 | 39 | 40 | `subprocess`模块可能更适合你. 41 | 42 | 最后请注意在你传递到shell的命令一定要注意参数的安全性,给你个提示,看下面代码 43 | 44 | ```python 45 | print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read() 46 | ``` 47 | 48 | 想象一下如果哪个 SB 输入 `my mama didnt love me && rm -rf /` 49 | 50 | -------------------------------------------------------------------------------- /part/60.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |60|1893|1895582|22| [url](http://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space) | 5 | *** 6 | 7 | ## 如何使打印的内容没有空格或换行 8 | 9 | 在 `c` 语言中我可以这么打印: 10 | 11 | ```c 12 | #include 13 | 14 | int main() { 15 | int i; 16 | for (i=0; i<10; i++) printf("."); 17 | return 0; 18 | } 19 | ``` 20 | 21 | 输出: 22 | 23 | ``` 24 | .......... 25 | ``` 26 | 27 | 在 Python 里: 28 | 29 | ```python 30 | >>> for i in xrange(0,10): print '.' 31 | . 32 | . 33 | . 34 | . 35 | . 36 | . 37 | . 38 | . 39 | . 40 | . 41 | >>> for i in xrange(0,10): print '.', 42 | . . . . . . . . . . 43 | ``` 44 | 45 | 在 Python 里 `print` 会加上 `\n` 或者空格, 如何避免? 46 | 47 | *** 48 | 49 | ### 通用做法 50 | 51 | ```python 52 | import sys 53 | sys.stdout.write('.') 54 | ``` 55 | 56 | 你也可以调用 57 | 58 | ```python 59 | sys.stdout.flush() 60 | ``` 61 | 62 | 来确保 `stdout` 立即刷新 63 | 64 | ### Python 2.6+ 65 | 66 | 在 Python2.6 里你可以引入 Python3 的 `print` 函数: 67 | 68 | ```python 69 | from __future__ import print_function 70 | ``` 71 | 72 | 这样可以用 Python3 来解决上面的问题 73 | 74 | ### Python3 75 | 76 | 在 Python3 中, `print` 语句变成了函数.在 Python3 中你可以: 77 | 78 | ```python 79 | print('.', end='') 80 | ``` 81 | 82 | 在 Python2 中也可以, 确保你引入 `from __future__ import print_function`. 83 | 84 | 如果你在缓冲遇到了麻烦, 你可以在后面加上 `flush=True` 参数: 85 | 86 | ```python 87 | print('.', end='', flush=True) 88 | ``` 89 | 90 | 注意 `flush` 关键字在 Python2 里引入 `__future__` 后并不生效;它只在 Python3 里, 更精确的说是 3.3 或以上.在老版本里你需要手动调用 `sys.stdout.flush()`. -------------------------------------------------------------------------------- /part/61.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |61|1870|259761|10| [url](http://stackoverflow.com/questions/9371238/why-is-reading-lines-from-stdin-much-slower-in-c-than-python) | 5 | *** 6 | 7 | ## 为什么在C++中读取stdin中的行会比Python慢呢? 8 | 9 | ps:这个是C++的问题了所以没做翻译. -------------------------------------------------------------------------------- /part/62.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |62|1844|1520739|13| [url](http://stackoverflow.com/questions/11277432/how-to-remove-a-key-from-a-python-dictionary) | 5 | *** 6 | 7 | ## 在 Python 中如何移除字典中的 key ? 8 | 9 | 当我想移除字典里的 key 时: 10 | 11 | ```python 12 | if 'key' in myDict: 13 | del myDict['key'] 14 | ``` 15 | 16 | 有没有一行就能实现的代码? 17 | 18 | *** 19 | 20 | 用 [dict.pop()](http://docs.python.org/library/stdtypes.html#dict.pop) 21 | 22 | ```python 23 | my_dict.pop('key', None) 24 | ``` 25 | 26 | 上面的代码如果 `key` 存在将会返回 `my_dict[key]`, 不存在就会返回 `None`.如果第二个参数没有指定(例如, `my_dict.pop('key')`),那么如果 `key` 不存在就会抛出 `KeyError` 异常. -------------------------------------------------------------------------------- /part/63.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |63|1807|1765599|13| [url](http://stackoverflow.com/questions/2225038/determine-the-type-of-an-object) | 5 | *** 6 | 7 | ## 查看一个对象的类型 8 | 9 | 有什么方便的方法查看一个对象的类型? 10 | 11 | *** 12 | 13 | 为了获得对象的类型,可以用内建函数`type()`.把对象作为唯一的参数传递将会返回这个对象的类型: 14 | 15 | ```python 16 | >>> type([]) is list 17 | True 18 | >>> type({}) is dict 19 | True 20 | >>> type('') is str 21 | True 22 | >>> type(0) is int 23 | True 24 | ``` 25 | 26 | 当然也对自定义类型也有用: 27 | 28 | ```python 29 | >>> class Test1 (object): 30 | pass 31 | >>> class Test2 (Test1): 32 | pass 33 | >>> a = Test1() 34 | >>> b = Test2() 35 | >>> type(a) is Test1 36 | True 37 | >>> type(b) is Test2 38 | True 39 | ``` 40 | 41 | 注意`type()`只会返回对象的直接类型,不会告诉你继承类型. 42 | 43 | ```python 44 | >>> type(b) is Test1 45 | False 46 | ``` 47 | 48 | 可以用`isinstance`函数.也对内建函数管用: 49 | 50 | ```python 51 | >>> isinstance(b, Test1) 52 | True 53 | >>> isinstance(b, Test2) 54 | True 55 | >>> isinstance(a, Test1) 56 | True 57 | >>> isinstance(a, Test2) 58 | False 59 | >>> isinstance([], list) 60 | True 61 | >>> isinstance({}, dict) 62 | True 63 | ``` 64 | 65 | `isinstance()`通常是确定一个对象类型更好的方法,因为它接受派生类型.所以除非你确实需要知道对象的类型(一些其他原因),用`isinstance()`比`type()`更好. 66 | 67 | `isinstance()`的第二个参数也接受类型的元组,所以也可以一次检查多种类型.如果是这些类型里的`isinstance()`将会返回true: 68 | 69 | ```python 70 | >>> isinstance([], (tuple, list, set)) 71 | True 72 | ``` -------------------------------------------------------------------------------- /part/64.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |64|1791|1428391|14| [url](http://stackoverflow.com/questions/306400/how-to-randomly-select-an-item-from-a-list) | 5 | *** 6 | 7 | ## 在列表中随机取一个元素 8 | 9 | 例如我有如下列表: 10 | 11 | ```python 12 | foo = ['a', 'b', 'c', 'd', 'e'] 13 | ``` 14 | 15 | 从列表中随机取一个元素最好的方法是什么? 16 | 17 | *** 18 | 19 | ```python 20 | import random 21 | 22 | foo = ['a', 'b', 'c', 'd', 'e'] 23 | print(random.choice(foo)) 24 | ``` -------------------------------------------------------------------------------- /part/65.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |65|1781|1289586|10| [url](http://stackoverflow.com/questions/493819/why-is-it-string-joinlist-instead-of-list-joinstring) | 5 | *** 6 | 7 | ## 为什么是string.join(list)而不是list.join(string)? 8 | 9 | 我一直被这个问题困扰.如果这样写更好: 10 | 11 | ```python 12 | my_list = ["Hello", "world"] 13 | print my_list.join("-") 14 | # Produce: "Hello-world" 15 | ``` 16 | 17 | 而不是: 18 | 19 | ```python 20 | my_list = ["Hello", "world"] 21 | print "-".join(my_list) 22 | # Produce: "Hello-world" 23 | ``` 24 | 25 | 有什么特殊的原因让它不这样做吗? 26 | 27 | *** 28 | 29 | 是因为所有的可迭代对象都能被`join`,不仅仅是列表,但结果是我们一般要`join`的都是字符串. 30 | 31 | 例如: 32 | 33 | ```python 34 | import urllib2 35 | print '\n############\n'.join(urllib2.urlopen('http://data.stackexchange.com/users/7095')) 36 | ``` -------------------------------------------------------------------------------- /part/66.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |66|1779|726218|14| [url](http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string) | 5 | *** 6 | 7 | ## 通过函数名的字符串来调用这个函数 8 | 9 | 假如我们有个模块叫`foo`,而我有一个`"bar"`字符串.调用`foo.bar()`有什么最好的方法? 10 | 11 | 我需要返回函数值,为什么我不能用`eval`.我想应该能用`eval`来定义一个函数来返回调用的结果,但是我希望更优雅的方法. 12 | 13 | *** 14 | 15 | 假设`foo`有一个`bar`方法: 16 | 17 | ```python 18 | import foo 19 | methodToCall = getattr(foo, 'bar') 20 | result = methodToCall() 21 | ``` 22 | 23 | 第二行和第三行可以简写: 24 | 25 | ```python 26 | result = getattr(foo, 'bar')() 27 | ``` 28 | 29 | 如果让上面的代码更有意义.`getattr`可以用在实例绑定,模块级方法,类方法...等等 -------------------------------------------------------------------------------- /part/67.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |67|1740|975262|10| [url](http://stackoverflow.com/questions/735975/static-methods-in-python) | 5 | *** 6 | 7 | ## 静态方法 8 | 9 | Python有没有静态方法使我可以不用实例化一个类就可以调用,像这样: 10 | 11 | ```python 12 | ClassName.StaticMethod ( ) 13 | ``` 14 | 15 | *** 16 | 17 | 是的,用[静态方法](https://docs.python.org/2/library/functions.html#staticmethod)装饰器 18 | 19 | ```python 20 | class MyClass(object): 21 | @staticmethod 22 | def the_static_method(x): 23 | print x 24 | 25 | MyClass.the_static_method(2) # outputs 2 26 | ``` 27 | 28 | 注意有些代码用一个函数而不是`staticmethod`装饰器去定义一个静态方法.如果你想支持Python的老版本(2.2和2.3)可以用下面的方法: 29 | 30 | ```python 31 | class MyClass(object): 32 | def the_static_method(x): 33 | print x 34 | the_static_method = staticmethod(the_static_method) 35 | 36 | MyClass.the_static_method(2) # outputs 2 37 | ``` 38 | 39 | 这个方法和第一个一样,只是没有第一个用装饰器的优雅. 40 | 41 | 最后,请少用`staticmethod`方法!在Python里只有很少的场合适用静态方法,其实许多顶层函数会比静态方法更清晰明了. 42 | 43 | [文档](https://docs.python.org/2/library/functions.html#staticmethod) -------------------------------------------------------------------------------- /part/68.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |68|1718|1588422|44| [url](http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python) | 5 | *** 6 | 7 | ## Python中用什么代替switch语句? 8 | 9 | 我想写一个函数,实现输入一个值对应输出另一个值. 10 | 11 | 在其他语言我可以用`switch`或者`case`语句,但是Python里没有`switch`.Python里如何解决这个问题? 12 | 13 | *** 14 | 15 | 你可以用一个字典: 16 | 17 | ```python 18 | def f(x): 19 | return { 20 | 'a': 1, 21 | 'b': 2, 22 | }[x] 23 | ``` 24 | 25 | *** 26 | 27 | 如果你希望设置一个默认值可以用字典的`get`方法: 28 | 29 | ```python 30 | def f(x): 31 | return { 32 | 'a': 1, 33 | 'b': 2, 34 | }.get(x, 9) # 9 is default if x not found 35 | ``` -------------------------------------------------------------------------------- /part/69.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |69|1716|3370415|26| [url](http://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points) | 5 | *** 6 | 7 | ## 限制浮点型到小数点后两位 8 | 9 | 我希望 `a` 可以转化成 13.95 10 | 11 | ```python 12 | >>> a 13 | 13.949999999999999 14 | >>> round(a, 2) 15 | 13.949999999999999 16 | ``` 17 | 18 | [round](https://docs.python.org/2/library/functions.html#round) 并没有像我期待的那样得到 13.95 19 | 20 | *** 21 | 22 | 你遇到了典型的浮点数问题,那就是浮点数并不能代表所有的数值.命令行展示的只是内存中的完整的浮点数的形式. 23 | 24 | 上面的浮点数和你想要的结果是等价的.因为计算机是二进制的,它将浮点数存为整形,并且除以2的幂,所以 13.95 将会表示成 125650429603636838/(2**53). 25 | 26 | 双精度数值有53个字节来表示精度,而浮点型有24个字节表示.Python 使用 [双精度浮点数](http://docs.python.org/tutorial/floatingpoint.html) 来存储数值. 27 | 28 | 例如, 29 | 30 | ```python 31 | >>> 125650429603636838/(2**53) 32 | 13.949999999999999 33 | 34 | >>> 234042163/(2**24) 35 | 13.949999988079071 36 | 37 | >>> a=13.946 38 | >>> print(a) 39 | 13.946 40 | >>> print("%.2f" % a) 41 | 13.95 42 | >>> round(a,2) 43 | 13.949999999999999 44 | >>> print("%.2f" % round(a,2)) 45 | 13.95 46 | >>> print("{0:.2f}".format(a)) 47 | 13.952 48 | >>> print("{0:.2f}".format(round(a,2))) 49 | 13.95 50 | >>> print("{0:.15f}".format(round(a,2))) 51 | 13.949999999999999 52 | ``` 53 | 54 | 如果你想要精确到小数点后2位有两个不错的选择: 55 | 56 | 1. 使用整数并以美分存储值,而不是美元,然后除以100转换为美元。(没看懂,可能是 Python 的货币计算?) 57 | 2. 使用 Python 的 [decimal](http://docs.python.org/library/decimal.html) -------------------------------------------------------------------------------- /part/7.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |7|4934|1901070|44| [url](http://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python-taking-union-o) | 5 | *** 6 | 7 | ## 如何在一个表达式里合并两个字典? 8 | 9 | 我有两个Python字典,我想写一个表达式来返回两个字典的合并.update()方法返回的是空值而不是返回合并后的对象. 10 | 11 | ```python 12 | >>> x = {'a':1, 'b': 2} 13 | >>> y = {'b':10, 'c': 11} 14 | >>> z = x.update(y) 15 | >>> print z 16 | None 17 | >>> x 18 | {'a': 1, 'b': 10, 'c': 11} 19 | ``` 20 | 21 | 怎么样才能最终让值保存在z而不是x? 22 | 23 | *** 24 | 25 | 可以用下面的方法: 26 | 27 | ``` 28 | z = dict(x.items() + y.items()) 29 | ``` 30 | 31 | 最后就是你想要的最终结果保存在字典z中,而键`b`的值会被第二个字典的值覆盖. 32 | 33 | ```python 34 | >>> x = {'a':1, 'b': 2} 35 | >>> y = {'b':10, 'c': 11} 36 | >>> z = dict(x.items() + y.items()) 37 | >>> z 38 | {'a': 1, 'c': 11, 'b': 10} 39 | ``` 40 | 41 | 如果你用的是Python3的话稍微有点麻烦: 42 | 43 | ```python 44 | >>> z = dict(list(x.items()) + list(y.items())) 45 | >>> z 46 | {'a': 1, 'c': 11, 'b': 10} 47 | ``` 48 | 49 | *** 50 | 51 | 还可以这样: 52 | 53 | ```python 54 | z = x.copy() 55 | z.update(y) 56 | ``` 57 | 58 | -------------------------------------------------------------------------------- /part/70.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |70|1709|1870588|28| [url](http://stackoverflow.com/questions/275018/how-can-i-remove-a-trailing-newline) | 5 | *** 6 | 7 | ## 如何移除换行符? 8 | 9 | 这是我用Python编程遇到的最多的问题了,所以我想放到stackoverflow好让我下次Google'chomp python'的时候能得到有用的答案. 10 | 11 | *** 12 | 13 | 试试`rstrip`方法: 14 | 15 | ```python 16 | >>> 'test string\n'.rstrip() 17 | 'test string' 18 | ``` 19 | 20 | 注意Python的`rstrip`方法将会默认去掉所有的空白符,而在Perl里只是删除换行符.如果只是删除换行符: 21 | 22 | ```python 23 | >>> 'test string \n'.rstrip('\n') 24 | 'test string ' 25 | ``` 26 | 27 | 同样也有`lstrip`和`strip`方法: 28 | 29 | ```python 30 | >>> s = " \n abc def " 31 | >>> s.strip() 32 | 'abc def' 33 | >>> s.rstrip() 34 | ' \n abc def' 35 | >>> s.lstrip() 36 | 'abc def ' 37 | >>> 38 | ``` -------------------------------------------------------------------------------- /part/71.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |71|1679|895303|14| [url](http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python) | 5 | *** 6 | 7 | ## 在 Python 中如何得到对象的所有属性? 8 | 9 | 有没有什么方法可以检测对象是否有一个属性?例如: 10 | 11 | ```python 12 | >>> a = SomeClass() 13 | >>> a.someProperty = value 14 | >>> a.property 15 | Traceback (most recent call last): 16 | File "", line 1, in 17 | AttributeError: SomeClass instance has no attribute 'property' 18 | ``` 19 | 20 | 怎么样才能在用 `porperty` 之前知道 `a` 有这个属性? 21 | 22 | *** 23 | 24 | 试试 [hasattr()](https://docs.python.org/3/library/functions.html#hasattr): 25 | 26 | ```python 27 | if hasattr(a, 'property'): 28 | a.property 29 | ``` 30 | 31 | 答案2 32 | 33 | `hasattr` 可以做到,但是我要说一句 Python 鼓励 "easier to ask for forgiveness than permission" (EAFP) 而不是 "look before you leap" (LBYL).详细查看下面链接: 34 | 35 | [EAFP vs LBYL (was Re: A little disappointed so far)](http://web.archive.org/web/20070929122422/http://mail.python.org/pipermail/python-list/2003-May/205182.html) 36 | [EAFP vs. LBYL @Code Like a Pythonista: Idiomatic Python](https://web.archive.org/web/20180411011411/http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#eafp-vs-lbyl) 37 | 38 | 例如: 39 | 40 | ```python 41 | try: 42 | doStuff(a.property) 43 | except AttributeError: 44 | otherStuff() 45 | ``` 46 | 47 | 要比下面的更好 48 | 49 | ```python 50 | if hasattr(a, 'property'): 51 | doStuff(a.property) 52 | else: 53 | otherStuff() 54 | ``` 55 | 56 | -------------------------------------------------------------------------------- /part/72.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |72|1675|2173501|21| [url](http://stackoverflow.com/questions/17271319/how-do-i-install-pip-on-macos-or-os-x) | 5 | *** 6 | 7 | ## 在 macOS 上如何安装 pip 8 | 9 | 昨天我花了许多时间研究怎么安装 `pip`, 但是没有找到方法 10 | 11 | 我该怎么安装它? 12 | 13 | *** 14 | 15 | ```python 16 | easy_install pip 17 | ``` 18 | 19 | 如果你需要管理员权限, 试一下: 20 | 21 | ```python 22 | sudo easy_install pip 23 | ``` -------------------------------------------------------------------------------- /part/73.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |73|1649|930869|12| [url](http://stackoverflow.com/questions/990754/how-to-leave-exit-deactivate-a-python-virtualenv) | 5 | *** 6 | 7 | ## 如何离开/退出/停用Python的virtualenv? 8 | 9 | 我正在用virtualenv和virtualenvwrapper.我能用命令很好的在virtualenv之间切换. 10 | 11 | ``` 12 | me@mymachine:~$ workon env1 13 | (env1)me@mymachine:~$ workon env2 14 | (env2)me@mymachine:~$ workon env1 15 | (env1)me@mymachine:~$ 16 | ``` 17 | 18 | 但是如何退出虚拟机回到自己的环境中?到目前位置只有一个方法: 19 | 20 | ``` 21 | me@mymachine:~$ 22 | ``` 23 | 24 | 就是退出shell再新建一个.这有点烦人.有没有现成的命令?如果没有我怎么创建它? 25 | 26 | *** 27 | 28 | 通常在虚拟环境中在shell中输入: 29 | 30 | ``` 31 | $ deactivate 32 | ``` 33 | 34 | 将会返回正常环境. -------------------------------------------------------------------------------- /part/74.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |74|1636|1393338|33| [url](http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float) | 5 | *** 6 | 7 | ## 检查一个字符串是否是一个数字 8 | 9 | 如果一个字符串可以被看做一个数字那么有什么好的方法可以检测出来? 10 | 11 | 我能想到的方法: 12 | 13 | ```python 14 | def is_number(s): 15 | try: 16 | float(s) 17 | return True 18 | except ValueError: 19 | return False 20 | ``` 21 | 22 | 我还没有想到什么更好的方法. 23 | 24 | *** 25 | 26 | 对字符串对象用`isdigit()`方法: 27 | 28 | ```python 29 | >>> a = "03523" 30 | >>> a.isdigit() 31 | True 32 | ``` 33 | 34 | ```python 35 | >>> b = "963spam" 36 | >>> b.isdigit() 37 | False 38 | ``` 39 | 40 | [String Methods - isdigit()](http://docs.python.org/library/stdtypes.html#str.isdigit) 41 | 42 | 同样也有unicode的方法,但是我不太熟悉[Unicode - Is decimal/decimal](http://docs.python.org/library/stdtypes.html#unicode.isnumeric) 43 | -------------------------------------------------------------------------------- /part/75.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |75|1615|2691500|16| [url](http://stackoverflow.com/questions/402504/how-to-determine-a-python-variables-type) | 5 | *** 6 | 7 | ## 如何查看 Python 变量的类型? 8 | 9 | *** 10 | 11 | Python 不像 C/C++,不会出现你的问题 12 | 13 | 试一下: 14 | 15 | ```python 16 | >>> i = 123 17 | >>> type(i) 18 | 19 | >>> type(i) is int 20 | True 21 | >>> i = 123456789L 22 | >>> type(i) 23 | 24 | >>> type(i) is long 25 | True 26 | >>> i = 123.456 27 | >>> type(i) 28 | 29 | >>> type(i) is float 30 | True 31 | ``` 32 | 33 | 在 Python3.0中 int 和 long 已经不再进行区分了. -------------------------------------------------------------------------------- /part/76.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |76|1614|623581|12| [url](http://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner) | 5 | *** 6 | 7 | ## 对于初学者如何理解 `@classmethod` 和 `@staticmethod`? 8 | 9 | 10 | *** 11 | 12 | 虽然 `classmethod` 和 `staticmethod` 非常接近, 但是用途却是不同: `classmethod` 必须把类对象的引用作为第一个参数,而 `staticmethod` 则不需要. 13 | 14 | ### 例子 15 | 16 | ```python 17 | class Date(object): 18 | 19 | def __init__(self, day=0, month=0, year=0): 20 | self.day = day 21 | self.month = month 22 | self.year = year 23 | 24 | @classmethod 25 | def from_string(cls, date_as_string): 26 | day, month, year = map(int, date_as_string.split('-')) 27 | date1 = cls(day, month, year) 28 | return date1 29 | 30 | @staticmethod 31 | def is_date_valid(date_as_string): 32 | day, month, year = map(int, date_as_string.split('-')) 33 | return day <= 31 and month <= 12 and year <= 3999 34 | 35 | date2 = Date.from_string('11-09-2012') 36 | is_date = Date.is_date_valid('11-09-2012') 37 | ``` 38 | 39 | ### 解释 40 | 41 | 让我们来创建一个处理日期的 class: 42 | 43 | ```python 44 | class Date(object): 45 | 46 | def __init__(self, day=0, month=0, year=0): 47 | self.day = day 48 | self.month = month 49 | self.year = year 50 | ``` 51 | 52 | 这个 class 很显然是用来存储特定日期的信息. 53 | 54 | 这里用 Python 的 `__init__` 来初始化类实例, 它可以接收参数作为一个 `instancemethod`, 它的第一个参数 `self` 是新建实例的引用. 55 | 56 | #### 类方法 57 | 58 | 我们可以用 `classmethod` 来很好的完成一些功能. 59 | 60 | 假设我们想通过一些形如 `dd-mm-yyyy` 的 string 来创建 `Date` 实例.而且我们需要在我们工程里许多不同的地方实现. 61 | 62 | 所以我们必须: 63 | 64 | 1. 解析 string 为天,月和年这3个整数或者3元元祖. 65 | 2. 通过传递这些值来完成 `Date` 的初始化调用 66 | 67 | ```python 68 | day, month, year = map(int, string_date.split('-')) 69 | date1 = Date(day, month, year) 70 | ``` 71 | 72 | 在 C++ 里可以用 overloading 的方法来实现, 但是 Python 里没有 overloading.取而代之的我们可以使用 `classmethod`.让我们来创建另一种 `constructor` 73 | 74 | ```python 75 | @classmethod 76 | def from_string(cls, date_as_string): 77 | day, month, year = map(int, date_as_string.split('-')) 78 | date1 = cls(day, month, year) 79 | return date1 80 | 81 | date2 = Date.from_string('11-09-2012') 82 | ``` 83 | 84 | 让我们仔细看看上面两个实现,来看看两个实现的优缺点: 85 | 86 | 1. 我们在一个地方实现了 date string 的转换并且可以复用. 87 | 2. 很好的封装(如果你认为或许可以实现一个函数来解析, 但是这么做更符合 OOP 设计) 88 | 3. `cls` 是一个承载 class 自己的对象, 并不是 class 的实例.这个非常好用,因为只要我们继承了 `Data` class, 所有的子类都拥有 `from_string` 这个方法. 89 | 90 | #### 静态方法 91 | 92 | `staticmethods` 呢?它非常像 `classmethod` 但是它不包含任何必须的参数(比如说类方法或者实例方法). 93 | 94 | 让我们看看下一个用法. 95 | 96 | 我们想验证一个 date string 的有效性,这个任务不需要绑定到实例上只需要绑定到类上面. 97 | 98 | `staticmethod` 对我们来说就比较好用了.我们看看下一段代码: 99 | 100 | ```python 101 | @staticmethod 102 | def is_date_valid(date_as_string): 103 | day, month, year = map(int, date_as_string.split('-')) 104 | return day <= 31 and month <= 12 and year <= 3999 105 | 106 | # usage: 107 | is_date = Date.is_date_valid('11-09-2012') 108 | ``` 109 | 110 | 所以我们看到 `staticmethod` 就想一个函数一样不需要指定 class,语法上的调用也非常像函数,没办法访问对象及其内部,而 `classmethod` 就可以. -------------------------------------------------------------------------------- /part/77.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |77|1604|1634991|12| [url](http://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file-in-python) | 5 | *** 6 | 7 | ## 如何增加文件的内容? 8 | 9 | 如何做到 append 文件而不是覆盖? 10 | 11 | *** 12 | 13 | ```python 14 | with open("test.txt", "a") as myfile: 15 | myfile.write("appended text") 16 | ``` -------------------------------------------------------------------------------- /part/78.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |78|1568|463004|16| [url](http://stackoverflow.com/questions/5466451/how-can-i-print-literal-curly-brace-characters-in-python-string-and-also-use-fo) | 5 | *** 6 | 7 | ## 如何在 .format 中使用大括号? 8 | 9 | ```python 10 | x = " \{ Hello \} {0} " 11 | print x.format(42) 12 | ``` 13 | 14 | 得到了: `Key Error: Hello\\` 15 | 16 | 我希望输出: `{Hello} 42` 17 | 18 | *** 19 | 20 | 你需要写两次, `{{` 和 `}}`: 21 | 22 | ```python 23 | >>> x = " {{ Hello }} {0} " 24 | >>> print x.format(42) 25 | ' { Hello } 42 ' 26 | ``` 27 | 28 | 文档在这里 [Python documentation for format string syntax](http://docs.python.org/library/string.html#formatstrings)" 29 | 30 | 格式化中的大括号 `{}` 表示替代字段.任何不再大括号中的将被看做文本,会被原样输出.如果你在文本中包含大括号, 你可以使用 `{{` 和 `}}`. 31 | -------------------------------------------------------------------------------- /part/79.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |79|1561|1740379|24| [url](http://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item) | 5 | *** 6 | 7 | ## 如何计算列表中元素出现的个数? 8 | 9 | *** 10 | 11 | 如果你想计算单个元素出现的次数,使用 `count` 方法: 12 | 13 | ```python 14 | >>> [1, 2, 3, 4, 1, 4, 1].count(1) 15 | 3 16 | ``` 17 | 18 | **不要**在计算多个元素时使用这个方法.每次调用 `count` 方法都会迭代一边列表,性能会很低,如果你需要计算所有的元素或者指定几个元素可以使用 `Counter`. 19 | 20 | ```python 21 | >>> from collections import Counter 22 | >>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] 23 | >>> Counter(z) 24 | Counter({'blue': 3, 'red': 2, 'yellow': 1}) 25 | ``` 26 | -------------------------------------------------------------------------------- /part/8.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |8|4324|2684453|25| [url](http://stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory) | 5 | *** 6 | 7 | ## 检查一个文件夹是否存在,如果不存在就创建它 8 | 9 | 有什么好的方法吗?这个是我想的: 10 | 11 | ```python 12 | filename = "/my/directory/filename.txt" 13 | dir = os.path.dirname(filename) 14 | 15 | try: 16 | os.stat(dir) 17 | except: 18 | os.mkdir(dir) 19 | 20 | f = file(filename) 21 | ``` 22 | 23 | 我忘记了`os.path.exists`(多谢张三,李四,王五的提醒).下面是更改的: 24 | 25 | ```python 26 | def ensure_dir(f): 27 | d = os.path.dirname(f) 28 | if not os.path.exists(d): 29 | os.makedirs(d) 30 | ``` 31 | 32 | 有什么"打开"的标记可以自动的运行? 33 | 34 | *** 35 | 36 | 我看了俩答案都很好,但是都有一点缺陷,所以给出我的: 37 | 38 | 先试`os.path.exists`,然后通过`os.makedirs`来创建. 39 | 40 | ```python 41 | if not os.path.exists(directory): 42 | os.makedirs(directory) 43 | ``` 44 | 45 | 标注一下-如果一个文件在调用`os.path.exists`和`os.makedirs`之间被创建了,将会出现一个`OSError`.遗憾的是捕获`OSError`异常继续进行并不是万无一失的,它将会忽略像磁盘空间不足,没有足够权限等一些其他造成文件创建失败的因素. 46 | 47 | 一个做法是捕获`OSError`异常并检查返回的错误代码(前提是知道错误代码对应的是什么).然而,还有另一种可能,第二次的`os.path.exists`.假如恰好在第一次检查的时候创建了文件夹,然后在第二次检查的时候删掉--我们被耍了~~ 48 | 49 | 根据不同的应用,并行操作的危险或多或少的比其他因素危险.开发者必须在选择开发环境的时候更多地了解特定的应用程序. -------------------------------------------------------------------------------- /part/80.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |80|1541|2672492|18| [url](http://stackoverflow.com/questions/627435/how-to-remove-an-element-from-a-list-by-index) | 5 | *** 6 | 7 | ## 如何删除 list 中指定 index 的元素? 8 | 9 | *** 10 | 11 | 使用 `del` 并且指定你想删除的元素的 index: 12 | 13 | ```python 14 | >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 15 | >>> del a[-1] 16 | >>> a 17 | [0, 1, 2, 3, 4, 5, 6, 7, 8] 18 | ``` 19 | 20 | 同时支持切片: 21 | 22 | ```python 23 | >>> del a[2:4] 24 | >>> a 25 | [0, 1, 4, 5, 6, 7, 8, 9] 26 | ``` -------------------------------------------------------------------------------- /part/81.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |81|1489|1661305|22| [url](http://stackoverflow.com/questions/1450393/how-do-you-read-from-stdin) | 5 | *** 6 | 7 | ## 在 Python 里如何读取 stdin? 8 | 9 | *** 10 | 11 | 可以使用 [`fileinput`](http://docs.python.org/library/fileinput.html): 12 | 13 | ```python 14 | import fileinput 15 | 16 | for line in fileinput.input(): 17 | pass 18 | ``` 19 | 20 | [`fileinput`](http://docs.python.org/library/fileinput.html) 命令可以迭代命令参数给出的文件的每一行, 如果没有给出参数则直接从标准输入中得到. -------------------------------------------------------------------------------- /part/82.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |82|1484|936725|17| [url](http://stackoverflow.com/questions/339007/how-to-pad-zeroes-to-a-string) | 5 | *** 6 | 7 | ## 给字符串填充0 8 | 9 | 有什么方法可以给字符串左边填充0,这样就可以有一个特定长度. 10 | 11 | *** 12 | 13 | 字符串: 14 | 15 | ```python 16 | >>> n = '4' 17 | >>> print n.zfill(3) 18 | >>> '004' 19 | ``` 20 | 21 | 对于数字: 22 | 23 | ```python 24 | >>> n = 4 25 | >>> print '%03d' % n 26 | >>> 004 27 | >>> print format(4, '03') # python >= 2.6 28 | >>> 004 29 | >>> print "{0:03d}".format(4) # python >= 2.6 30 | >>> 004 31 | >>> print("{0:03d}".format(4)) # python 3 32 | >>> 004 33 | ``` 34 | 35 | *** 36 | 37 | ```python 38 | >>> t = 'test' 39 | >>> t.rjust(10, '0') 40 | >>> '000000test' 41 | ``` 42 | -------------------------------------------------------------------------------- /part/83.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |83|1477|1563435|28| [url](http://stackoverflow.com/questions/4383571/importing-files-from-different-folder) | 5 | -------------------------------------------------------------------------------- /part/84.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |84|1472|971303|9| [url](http://stackoverflow.com/questions/510972/getting-the-class-name-of-an-instance) | 5 | *** 6 | 7 | ## 如何获取实例的类名 8 | 9 | 如何才能获取一个实例对象的类名? 10 | 11 | 我想或许[the inspect module](https://docs.python.org/library/inspect)可以实现,但是好像还没有发现什么能帮我的.或许可以分析`__class__`成员,但是我不知道怎么用. 12 | 13 | *** 14 | 15 | 你试没试类里的`__name__`属性?比如`x.__class__.__name__`或许可以得到你想要的 16 | 17 | ```python 18 | >>> import itertools 19 | >>> x = itertools.count(0) 20 | >>> x.__class__.__name__ 21 | 'count' 22 | ``` 23 | 24 | 注:如果你用的是新式类(从Python2.2),你可以调用`type()`函数来替代: 25 | 26 | ```python 27 | >>> type(x).__name__ 28 | 'count' 29 | ``` 30 | 31 | 像`int`这种内建方法也可以: 32 | 33 | ```python 34 | >>> (5).__class__.__name__ 35 | 'int' 36 | >>> type(5).__name__ 37 | 'int' 38 | ``` -------------------------------------------------------------------------------- /part/85.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |85|1459|1657131|15| [url](http://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary) | 5 | -------------------------------------------------------------------------------- /part/86.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |86|1450|1764723|25| [url](http://stackoverflow.com/questions/9573244/how-to-check-if-the-string-is-empty) | 5 | *** 6 | 7 | ## 检查字符串为空的最优雅的方法 8 | 9 | *** 10 | 11 | 空字符串被认为是 [falsy](http://docs.python.org/2/library/stdtypes.html#truth-value-testing), 意味着转化成布尔类型值为 false, 所以你可以: 12 | 13 | ```python 14 | if not myString: 15 | ``` 16 | 17 | 在 [Truth Value Testing](http://docs.python.org/library/stdtypes.html#truth-value-testing)可以查询到其他变量转化成布尔类型对应的值. -------------------------------------------------------------------------------- /part/87.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |87|1445|2640604|9| [url](http://stackoverflow.com/questions/2835559/why-cant-python-parse-this-json-data) | 5 | *** 6 | 7 | ## 如何解析一个 JSON 文件? 8 | 9 | 我又一个如下的 JSON 文件: 10 | 11 | ```json 12 | { 13 | "maps": [ 14 | { 15 | "id": "blabla", 16 | "iscategorical": "0" 17 | }, 18 | { 19 | "id": "blabla", 20 | "iscategorical": "0" 21 | } 22 | ], 23 | "masks": [ 24 | "id": "valore" 25 | ], 26 | "om_points": "value", 27 | "parameters": [ 28 | "id": "valore" 29 | ] 30 | } 31 | ``` 32 | 33 | 我写了如下代码来打印所有的 json 文本: 34 | 35 | ```python 36 | json_data=open(file_directory).read() 37 | 38 | data = json.loads(json_data) 39 | pprint(data) 40 | ``` 41 | 42 | 如何才能解析文件并且得到单个的值? 43 | 44 | *** 45 | 46 | 额,你的 JSON 文件有错误.在应当用 `{}` 的地方使用了 `[]`. `[]` 是列表, `{}` 是字典. 47 | 48 | 下面是正确的形式: 49 | 50 | ```json 51 | { 52 | "maps": [ 53 | { 54 | "id": "blabla", 55 | "iscategorical": "0" 56 | }, 57 | { 58 | "id": "blabla", 59 | "iscategorical": "0" 60 | } 61 | ], 62 | "masks": { 63 | "id": "valore" 64 | }, 65 | "om_points": "value", 66 | "parameters": { 67 | "id": "valore" 68 | } 69 | } 70 | ``` 71 | 72 | 你可以用如下代码: 73 | 74 | ```python 75 | import json 76 | from pprint import pprint 77 | 78 | with open('data.json') as f: 79 | data = json.load(f) 80 | 81 | pprint(data) 82 | ``` 83 | 84 | 你可以使用 `data` 来得到你想要的值: 85 | 86 | ```python 87 | data["maps"][0]["id"] 88 | data["masks"]["id"] 89 | data["om_points"] 90 | ``` -------------------------------------------------------------------------------- /part/88.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |88|1426|868944|11| [url](http://stackoverflow.com/questions/3394835/use-of-args-and-kwargs) | 5 | *** 6 | 7 | ## `*args`和 `**kwargs` 8 | 9 | 我对`*args`和`**kwargs`的概念有点不理解. 10 | 11 | 到目前位置我了解到: 12 | 13 | * `*args` = 参数列表-作为可选参数 14 | * `**kwargs` = 字典-参数的关键字作为键,它们的值作为字典的值. 15 | 16 | ?? 17 | 18 | 说实话我不裂解这对编程来说有什么用?(我知道它,但是对他不了解.) 19 | 20 | 或许: 21 | 22 | 我想把字典或者列表当做参数的同时也把它们当成通配符,所以可以传递任何参数? 23 | 24 | 有什么实际例子来解释怎么用`*args`和`**kwargs`? 25 | 26 | 通过教程我只是用了"*"和一个变量名. 27 | 28 | 还是`*args`和`**kwargs`只是一个占位符,你们在代码里用`*args`和`**kwargs`吗? 29 | 30 | *** 31 | 32 | [`*`和`**`的语法](http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists).用`*args`和`**kwargs`只是为了方便并没有强制使用它们. 33 | 34 | 当你不确定你的函数里将要传递多少参数时你可以用`*args`.例如,它可以传递任意数量的参数: 35 | 36 | ```python 37 | >>> def print_everything(*args): 38 | for count, thing in enumerate(args): 39 | ... print '{0}. {1}'.format(count, thing) 40 | ... 41 | >>> print_everything('apple', 'banana', 'cabbage') 42 | 0. apple 43 | 1. banana 44 | 2. cabbage 45 | ``` 46 | 47 | 相似的,`**kwargs`允许你使用没有事先定义的参数名: 48 | 49 | ```python 50 | >>> def table_things(**kwargs): 51 | ... for name, value in kwargs.items(): 52 | ... print '{0} = {1}'.format(name, value) 53 | ... 54 | >>> table_things(apple = 'fruit', cabbage = 'vegetable') 55 | cabbage = vegetable 56 | apple = fruit 57 | ``` 58 | 59 | 你也可以混着用.命名参数首先获得参数值然后所有的其他参数都传递给`*args`和`**kwargs`.命名参数在列表的最前端.例如: 60 | 61 | ```python 62 | def table_things(titlestring, **kwargs) 63 | ``` 64 | 65 | `*args`和`**kwargs`可以同时在函数的定义中,但是`*args`必须在`**kwargs`前面. 66 | 67 | 当调用函数时你也可以用`*`和`**`语法.例如: 68 | 69 | ```python 70 | >>> def print_three_things(a, b, c): 71 | ... print 'a = {0}, b = {1}, c = {2}'.format(a,b,c) 72 | ... 73 | >>> mylist = ['aardvark', 'baboon', 'cat'] 74 | >>> print_three_things(*mylist) 75 | a = aardvark, b = baboon, c = cat 76 | ``` 77 | 78 | 就像你看到的一样,它可以传递列表(或者元组)的每一项并把它们解包.注意必须与它们在函数里的参数相吻合.当然,你也可以在函数定义或者函数调用时用`*`. -------------------------------------------------------------------------------- /part/89.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |89|1418|682095|191| [url](http://stackoverflow.com/questions/101268/hidden-features-of-python) | 5 | -------------------------------------------------------------------------------- /part/9.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |9|3684|2171883|21| [url](http://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) | 5 | *** 6 | 7 | ## 在循环中获取索引(数组下标) 8 | 9 | 有人知道如何获取列表的索引值吗: 10 | 11 | ```python 12 | ints = [8, 23, 45, 12, 78] 13 | ``` 14 | 15 | 当我循环这个列表时如何获得它的索引下标? 16 | 17 | *** 18 | 19 | 如果像C或者PHP那样加入一个状态变量那就太不pythonic了. 20 | 21 | 最好的选择就是用内建函数[enumerate](https://docs.python.org/2/library/functions.html#enumerate) 22 | 23 | ```python 24 | for idx, val in enumerate(ints): 25 | print idx, val 26 | ``` 27 | 28 | 想了解更多可以查看[PEP279].在Python2.x和Python3.x都好使. -------------------------------------------------------------------------------- /part/90.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |90|1407|1851506|15| [url](http://stackoverflow.com/questions/13411544/delete-column-from-pandas-dataframe) | 5 | -------------------------------------------------------------------------------- /part/91.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |91|1379|3422957|12| [url](http://stackoverflow.com/questions/961632/converting-integer-to-string) | 5 | *** 6 | 7 | ## 整数转化为字符串 8 | 9 | 我希望将整数转为 string,我试了如下方法: 10 | 11 | ```python 12 | d = 15 13 | d.str() 14 | ``` 15 | 16 | 但是提示 `int` 没有 `str` 方法 17 | 18 | *** 19 | 20 | ```python 21 | 1641 22 | down vote 23 | accepted 24 | >>> str(10) 25 | '10' 26 | >>> int('10') 27 | 1 28 | ``` 29 | 30 | 文档链接 31 | 32 | * [`int()`](https://docs.python.org/2/library/functions.html#int) 33 | * [`str`](https://docs.python.org/2/library/functions.html#str) 34 | 35 | 问题来自这个代码: `d.str()`. 36 | 37 | 转换是使用的内建 `str()` 函数,调用的是其参数的 `__str__()` 方法 -------------------------------------------------------------------------------- /part/92.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |92|1367|1933416|19| [url](http://stackoverflow.com/questions/3996904/generate-random-integers-between-0-and-9) | 5 | -------------------------------------------------------------------------------- /part/93.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |93|1367|866122|15| [url](http://stackoverflow.com/questions/5574702/how-to-print-to-stderr-in-python) | 5 | *** 6 | 7 | ## 输出到stderr 8 | 9 | 我知道至少三种方法这么做: 10 | 11 | ```python 12 | import sys 13 | sys.stderr.write('spam\n') 14 | 15 | print >> sys.stderr, 'spam' 16 | 17 | from __future__ import print_function 18 | print('spam', file=sys.stderr) 19 | ``` 20 | 21 | 但是看起来和python的第13条宗旨相违背,所以有什么更好的方法吗?或者上面那些方法有什么可以改进? 22 | 23 | >There should be one — and preferably only one — obvious way to do it. 24 | 25 | *** 26 | 27 | 我发现只有这个方法短小+便捷+可读性好: 28 | 29 | ```python 30 | from __future__ import print_function 31 | def warning(*objs): 32 | print("WARNING: ", *objs, file=sys.stderr) 33 | ``` 34 | 35 | *** 36 | 37 | 我会选择`sys.stderr.write()`,更可读而且言简意赅的突出重点,最主要的是在所有版本都可以用. 38 | 39 | 注:`Pythonic`是除了可读和效率意外才考虑的事情...如果记住前两条的话80%的代码就已经是`Pythonic`了.列表推导式是一个'big thing'所以不经常用(可读性). -------------------------------------------------------------------------------- /part/94.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |94|1363|1463625|11| [url](http://stackoverflow.com/questions/5226311/installing-specific-package-versions-with-pip) | 5 | -------------------------------------------------------------------------------- /part/95.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |95|1361|1278391|28| [url](http://stackoverflow.com/questions/931092/reverse-a-string-in-python) | 5 | *** 6 | 7 | ## 反转字符串 8 | 9 | 在Python里`str`没有内建的`reverse`函数.实现字符串反转最好的方法是什么? 10 | 11 | 如果答案很简单的话,那么最有效的是什么.是不是`str`要转换成一个不同的对象. 12 | 13 | *** 14 | 15 | 这个怎么样: 16 | 17 | ```python 18 | >>> 'hello world'[::-1] 19 | 'dlrow olleh' 20 | ``` 21 | 22 | 这是拓展的[切片](http://docs.python.org/2/whatsnew/2.3.html#extended-slices)语法.用`[begin:end:step]`实现-从begin开始到end结束步长是-1的话就可以反转一个字符串. -------------------------------------------------------------------------------- /part/96.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |96|1355|893485|30| [url](http://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits) | 5 | *** 6 | 7 | ## 生成包含大写字母和数字的随机字符串 8 | 9 | 我希望生成N大小的字符串. 10 | 11 | 里面只含有数字和大写字母,比如: 12 | 13 | * 6U1S75 14 | * 4Z4UKK 15 | * U911K4 16 | 17 | 有没有什么[Pythonic](https://en.wikipedia.org/wiki/Python_%28programming_language%29#Features_and_philosophy)的方法? 18 | 19 | *** 20 | 21 | 一行写的答案: 22 | 23 | ```python 24 | ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) 25 | ``` 26 | 27 | 为了重用可以这样写: 28 | 29 | ```python 30 | >>> import string 31 | >>> import random 32 | >>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits): 33 | ... return ''.join(random.choice(chars) for _ in range(size)) 34 | ... 35 | >>> id_generator() 36 | 'G5G74W' 37 | >>> id_generator(3, "6793YUIO") 38 | 'Y3U' 39 | ``` 40 | 41 | #### 如何工作? 42 | 43 | 我们引入`string`和`random`模块,`string`模块包含了所有常用的ASCII字符,`random`模块处理随机数的生成. 44 | 45 | `string.ascii_uppercase + string.digits`是一个包含大写字母和数字的列表: 46 | 47 | ```python 48 | >>> string.ascii_uppercase 49 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 50 | >>> string.digits 51 | '0123456789' 52 | >>> string.ascii_uppercase + string.digits 53 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' 54 | ``` 55 | 56 | 然后我们用列表推导式创建`n`个元素的列表: 57 | 58 | ```python 59 | >>> range(4) # n个数字的列白哦 60 | [0, 1, 2, 3] 61 | >>> ['elem' for _ in range(4)] # 在一个列表创建4次'elem' 62 | ['elem', 'elem', 'elem', 'elem'] 63 | ``` 64 | 65 | 在上面的例子中,我们用`[]`来创建列表,和`id_generator`函数不一样,生成器不再内存中创建列表,只是在程序运行时一个一个的生成列表元素(更多见[这里](http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained/231855#231855)) 66 | 67 | 下面是在列表中随机取出一个元素: 68 | 69 | ```python 70 | >>> random.choice("abcde") 71 | 'a' 72 | >>> random.choice("abcde") 73 | 'd' 74 | >>> random.choice("abcde") 75 | 'b' 76 | ``` 77 | 78 | 所以`random.choice(chars) for _ in range(size)`会取出`size`个字符.字符随机的在`chars`中取出: 79 | 80 | ```python 81 | >>> [random.choice('abcde') for _ in range(3)] 82 | ['a', 'b', 'b'] 83 | >>> [random.choice('abcde') for _ in range(3)] 84 | ['e', 'b', 'e'] 85 | >>> [random.choice('abcde') for _ in range(3)] 86 | ['d', 'a', 'c'] 87 | ``` 88 | 89 | 然后我们可以用空字符串把它们连起来成为一个字符串: 90 | 91 | ```python 92 | >>> ''.join(['a', 'b', 'b']) 93 | 'abb' 94 | >>> [random.choice('abcde') for _ in range(3)] 95 | ['d', 'c', 'b'] 96 | >>> ''.join(random.choice('abcde') for _ in range(3)) 97 | 'dac' 98 | ``` -------------------------------------------------------------------------------- /part/97.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |97|1355|985061|16| [url](http://stackoverflow.com/questions/5082452/string-formatting-vs-format) | 5 | *** 6 | 7 | ## 字符串格式化:%和.format 8 | 9 | Python2.6推出了[str.format()]方法,和原有的%格式化方式有小小的区别.那个方法更好? 10 | 11 | 1. 下面的方法有同样的输出,它们的区别是什么? 12 | 13 | ``` 14 | #!/usr/bin/python 15 | sub1 = "python string!" 16 | sub2 = "an arg" 17 | 18 | a = "i am a %s" % sub1 19 | b = "i am a {0}".format(sub1) 20 | 21 | c = "with %(kwarg)s!" % {'kwarg':sub2} 22 | d = "with {kwarg}!".format(kwarg=sub2) 23 | 24 | print a # "i am a python string!" 25 | print b # "i am a python string!" 26 | print c # "with an arg!" 27 | print d # "with an arg!" 28 | ``` 29 | 2. 另外在Python中格式化字符串什么时候执行?例如如果我的loggin的优先级设置为高,那么我还能用`%`操作符吗?如果是这样的话,有什么方法可以避免吗? 30 | 31 | log.debug("some debug info: %s" % some_info) 32 | 33 | *** 34 | 35 | 先回答第一个问题...`.format`在许多方面看起来更便利.你可以重用参数,但是你用`%`就不行.最烦人的是`%`它无法同时传递一个变量和元组.你可能会想下面的代码不会有什么问题: 36 | 37 | "hi there %s" % name 38 | 39 | 但是,如果`name`恰好是`(1,2,3)`,它将会抛出一个`TypeError`异常.为了保证它总是正确的,你必须这样做: 40 | 41 | "hi there %s" % (name,) # 提供一个单元素的数组而不是一个参数 42 | 43 | 但是有点丑.`.format`就没有这些问题.你给的第二个问题也是这样,`.format`好看多了. 44 | 45 | 你为什么不用它? 46 | 47 | * 不知道它(在读这个之前) 48 | * 为了和Python2.5兼容 49 | 50 | 回答你的第二个问题,字符串格式和其他操作一样发生在它们运行的时候.Python是非懒惰语言,在函数调用前执行表达式,所以在你的`log.debug`例子中,`"some debug info: %s"%some_info`将会先执行,先生成`"some debug info: roflcopters are active"`,然后字符串将会传递给`log.debug()` -------------------------------------------------------------------------------- /part/98.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |98|1334|979821|24| [url](http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python) | 5 | -------------------------------------------------------------------------------- /part/99.md: -------------------------------------------------------------------------------- 1 | 2 | | rank | vote | view | answer | url | 3 | |:-:|:-:|:-:|:-:|:-:| 4 | |99|1334|1171947|26| [url](http://stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-string) | 5 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | import re 6 | 7 | path = "/Users/limbo/github/stackoverflow_python/part1" 8 | create_path = "/Users/limbo/github/stackoverflow_python/data" 9 | 10 | 11 | def create_file(path, name, content): 12 | with open('{}/{}'.format(path, name), 'w') as F: 13 | F.write(content) 14 | 15 | files= os.listdir(path) 16 | 17 | for name in files: 18 | with open(path + "/" + name, "r") as F: 19 | pre_content = "" 20 | content = "" 21 | flag = 0 22 | for line in F.readlines(): 23 | if line.startswith('***'): 24 | flag = 1 25 | 26 | if flag: 27 | content += line 28 | else: 29 | pre_content += line 30 | 31 | pid = re.search(r"http://stackoverflow.com/questions/(\d+)/", pre_content).group(1) 32 | name = pid + ".md" 33 | create_file(create_path, name, content) 34 | --------------------------------------------------------------------------------