Built-in Functions
| name | description |
|---|---|
| abs | Return the absolute value of a number. |
| all | Return True if all elements of the iterable are true . |
| any | Return True if any element of the iterable is true. |
| ascii | Return a string containing a printable representation of an object. |
| bin | Convert an integer number to a binary string. |
| bool | Return a Boolean value, one of True or False. |
| breakpoint | Drops into the debugger at the call site. |
| bytearray | Return a new array of bytes. (0 <= x < 256) |
| bytes | Return a new “bytes” object. (0 <= x < 256) |
| callable | Return True if the object argument appears callable, False if not. |
| chr | Return the string representing a character whose Unicode code point is the integer i. |
| classmethod | Transform a method into a class method. C.f() |
| compile | Compile the source into a code or AST object. (executed by exec() or eval()) |
| delattr | Deletes the named attribute, provided the object allows it. |
| dict | Create a new dictionary. |
| dir | |
| divmod | |
| enumerate | Return an enumerate object. |
| eval | |
| exec | Dynamic execution of Python code |
| filter | |
| float | |
| format | |
| frozenset | |
| getattr | |
| globals | |
| hasattr | |
| hash | |
| help | |
| hex | |
| id | |
| input | |
| int | |
| isinstance | |
| issubclass | |
| iter | |
| len | |
| list | |
| locals | |
| map | |
| max | |
| memoryview | |
| min | |
| next | |
| object | |
| oct | |
| open | |
| ord | |
| pow | |
| property | |
| range | |
| repr | |
| reversed | |
| round | |
| set | |
| setattr | |
| slice | |
| sorted | |
| staticmethod | |
| str | |
| sum | |
| super | |
| tuple | |
| type | |
| vars | |
| zip | |
| import |
Functional Programming Modules
itertools : Functions creating iterators for efficient looping
| name | description | example |
|---|---|---|
| count | start, start+step … | count(1) –> 1 2 3 … |
| cycle | p0, p1, … , p0, p1, … | cycle(‘ABC’) –> A B C A B C … |
| repeat | elem, elem, … endlessly or up to n times | repeat(10, 3) –> 10 10 10 |
| accumulate | p0, p0+p1, p0+p1+p2, … | accumulate([1,2,3,4,5]) –> 1 3 6 10 15 |
| chain | p0, p1, … q0, q1, … | chain(‘ABC’, ‘DEF’) –> A B C D E F |
| chain.from_iterable | p0, p1, … q0, q1, … | chain.from_iterable([‘AB’, ‘DE’]) –> A B D E |
| compress | (d[0] if s[0]), (d[1] if s[1]), … | compress(‘ABCDE’, [1,0,1,0,1]) –> A C E |
| dropwhile | seq[n], seq[n+1], starting when pred fails | dropwhile(lambda x: x<5, [1,4,6,4,1]) –> 6 4 1 |
| filterfalse | elem of seq where pred(elem) is false | filterfalse(lambda x: x%2, range(5)) –> 0 2 4 |
| groupby | sub-iterators grouped by value of key(v) | |
| islice | elements from seq[start:stop:step] | |
| starmap | func(seq[0]), func(seq[1]), … | |
| takewhile | seq[0], seq[1], until pred fails | |
| tee | it1, it2, … itn splits one iterator into n | |
| zip_longest | (p[0], q[0]), (p[1], q[1]), … | zip_longest(‘AB’, ‘x’, fillvalue=’-‘) –> Ax B- |
functools : Higher-order functions and operations on callable objects
| name | description | example |
|---|---|---|
operator : Standard operators as functions
| name | description | example |
| —- | :———– | :——— |
||||
||||
||||
||||
||||
||||
||||
##IPython
IPython (interactive Python) 作为一个增强的 Python 解释器致力于提供“科学计算的全生命周期开发工具”。如果将 Python 看作数据科学任务的引擎,那么 IPython 就是一个交互式控制面板。IPython 被紧密地连接在 Jupyter 项目中,提供一个基于浏览器的 Notebook。Jupyter Notebook 不仅可以执行 Python/IPython 语句,还允许用户添加格式化文本、静态和动态的可视化图像、数学公式、JavaScript 插件等等。
用符号?获取文档
每一个 Python 对象都有一个字符串的引用(docstring),该字符串包含对象的简要介绍和使用方法。
1 | In [1]: len? |
通过符号??获取源代码
IPython 提供了获取源代码, 两个问好 (??),就是比看 doc 多一些好奇~:
1 | In [13]: def swap(x, y): return y,x |
用Tab补全的方式探索模块
IPython 用 Tab 键自动补全和探索对象、模块及命名空间的内容。
通配符匹配
IPython 提供了用 * 符号来实现的通配符匹配方法。
1 | In [15]: *Warning? |
| command | description |
|---|---|
| Ctrl + a | 将光标移到本行的开始处 |
| Ctrl + e | 将光标移到本行的结尾处 |
| Ctrl + b | 将光标回退一个字符 |
| Ctrl + f | 将光标前进一个字符 |
| Backspace | 删除前一个字符 |
| Ctrl + d | 删除后一个字符 |
| Ctrl + k | 从光标开始剪切至行的末尾 |
| Ctrl + u | 从行的开头剪切至光标 |
| Ctrl + y | 粘贴剪切的文本 |
| Ctrl + t | 交换前两个字符 |
| Ctrl + p | 获取前一个历史命令 |
| Ctrl + n | 获取后一个历史命令 |
| Ctrl + r | 对历史命令的反向搜索 |
| Ctrl + l | 清除终端屏幕的内容 |
| Ctrl + c | 中断当前的 Python 命令 |
| Ctrl + d | 退出 IPython 会话 |
粘贴代码块:%paste和%cpaste
执行外部代码:%run
计算代码运行时间:%timeit
魔法函数的帮助:?、%magic和%lsmagic
IPython的输入和输出对象
下划线快捷键和以前的输出
代码段计时:%timeit和%time
分析整个脚本:%prun
用%lprun进行逐行分析
用%memit和%mprun进行内存分析
更新 pip & setuptools
1 | python -m pip install -U pip setuptools |
30段极简Python代码:这些小技巧你都Get了吗
重复元素判定
1 | def all_unique(lst): |
字符元素组成判定
1 | from collections import Counter |
内存占用
1 | import sys |
字节占用
1 | def byte_size(string): |
打印 N 次字符串
1 | n = 2; |
大写第一个字母
1 | s = "programming is awesome" |
分块
1 | from math import ceil |
压缩
1 | def compact(lst): |
解包
1 | array = [['a', 'b'], ['c', 'd'], ['e', 'f']] |
链式对比
1 | a = 3 |
逗号连接
1 | hobbies = ["basketball", "football", "swimming"] |
元音统计
1 | import re |
首字母小写
1 | def decapitalize(string): |
展开列表
1 | def spread(arg): |
列表的差
1 | def difference(a, b): |
通过函数取差
1 | def difference_by(a, b, fn): |
链式函数调用
1 | def add(a, b): |
检查重复项
1 | def has_duplicates(lst): |
合并两个字典
1 | def merge_two_dicts(a, b): |
将两个列表转化为字典
1 | def to_dictionary(keys, values): |
使用枚举
1 | list = ["a", "b", "c", "d"] |
执行时间
1 | import time |
1 | ``` |
1 |
1 |
1 |
1 |
1 |
1 |
1 |
1 |
1 |
1 |
1 |
|
import pandas as pd
import numpy as np
df = pd.read_csv(“big_data.csv”, skiprows = lambda x: x>0 and np.random.rand() > 0.01)
print(“The shape of the df is {}. It has been reduced 100 times!”.format(df.shape))`
某列上使用 replace 方法和正则,快速完成值的清洗。
Reference :