python-30-seconds
[TOC]

Introduction

Note for python knowledges that you may not know, or you may not really know.
Inspired by 30-seconds-of-code

You May not Know

Python sys

stdin is used for all interactive input
1
import sys
2
3
for line in sys.stdin:
4
print(line)
Copied!

PEP

Python Enhancement Proposals. Python 增强提案。
Demo:

中文做变量

Python3 允许 non-ASCII identifiers in source code,任何 Unicode 字符,都可以作为变量,也就是说,中文也可以作为变量
1
姓名 = "wansho"
2
年龄 = 25
3
print(姓名)
Copied!

deep / shallow copy

What is shallow copy:
1
lst1 = [1, 2, 3]
2
3
def func(lst):
4
lst[0] += 1
5
6
print(id(lst1)) # 1499657981640
7
func(lst1)
8
print(id(lst1)) # 1499657981640
9
print(lst1) # [2, 2, 3]
10
11
"""
12
由于只传入了 lst1 的引用,所以 func 内 lst 就是 lst1,并没有创建一个新的对象(内存)
13
"""
Copied!
What is deep copy:
1
lst1 = [1, 2, 3]
2
lst2 = list(lst1)
3
4
print(id(lst1)) # 1499658012360
5
print(id(lst2)) # 1499658044872
6
7
"""
8
list() 开辟了一个新的内存,创建了一个新的对象,此为深拷贝,类似的构造方法为 深拷贝的 built-in class 还有很多
9
"""
Copied!
deep copy built-in classes:
1
list()
2
dict()
3
# 这些 callable object 实际上都是在调用构造方法进行对象的创建,其肯定为 深拷贝
Copied!

method vs function

What is method: Class 中定义的函数叫做 method
1
class MyClass():
2
def first_method():
3
return "first_method"
Copied!
What is function: 最外层定义的函数叫做 function
1
import pandas as pd
2
3
def get_columns(pd_data):
4
return pd_data.columns.tolist()
Copied!

built-in functions

ord()

get the unicode code point of given char. DOC
1
print(ord("a")) # 97
2
print(ord('€')) # 8364
Copied!

divmod()

除法,返回倍数和余数。
1
divmod(20, 8) # return (2, 4)
2
divmod(21.2, 8) # return (2.0, 5.199999999999999)
Copied!

enumerate()

enumerate() 用于给 sequence 生成 index
1
# enumerate 方法会对 sequence 进行封装,并返回一个可迭代的对象,其中的每一个 item 都是 tuple (index, sequence[index])
2
for index, value in enumerate(["a", "b", "c"]):
3
print(index, value)
4
5
"""
6
0 a
7
1 b
8
2 c
9
"""
Copied!

functools.reduce(), all(), any()

The common idea of reduce is to apply some operation to successive items in a sequence, accumulating previous result, thus reducing a sequence of values to a single value.
reduce 用于对一个 sequence 进行 successive compute,从而得到一个 single value。也就是通常所说的:降维(从 二维 到 一维)。
reduce
1
from functools import reduce
2
from operator import add, sub
3
4
reduce(add, range(10)) # 等价于 0 + 1 + 2 + …… + 9
5
reduce(sub, [1,2,3]) # 等价于 1 - 2 - 3
Copied!
Other reducing built-ins:
1
all(iterable) # return true if all value is true
2
any(iterable) # return true if one value is true
3
4
all(["1", [1], (1), {1:2}]) # true
5
all(["1", [1], (1), {}]) # false
6
7
any(["1", [1], (1), {}]) # true
Copied!

callable()

How to determine whether an object is callable?
1
[callable(obj) for obj in (abs, str, 13)]
2
# print [True, True, False]
Copied!

dir()

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
1
dir([1,2,3])
2
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Copied!
dir() 通常用于窥探一个对象的属性或者当前环境。

built-in operators

指数^: **

1
print(10 ** 2) # 10^2 = 100
2
print(2 ** 10) # 2^10 = 1024
Copied!

built-in modules

array.array

array.array is a mutable, flat sequence sequence in python. 其适合用来存储数值。
1
from array import array
2
from random import random
3
4
# 用生成表达式生成一个双精度的 float 类型 array, 其中包含有 1000 万个元素
5
# array 接受两个参数,第一个参数是存储的数据类型,第二个参数是存储的数据
6
# array 目前接受的存储类型为:
7
# I: integer 整形
8
# u: unicode 类型
9
# d: double 类型
10
floats = array("d", (random() for i in range(10**7)))
11
print("the last number: " + str(floats[-1]))
12
fw = open("array.bin", "wb")
13
floats.tofile(fw) # 讲数据写入二进制文件中
14
fw.close()
15
16
# 构建一个空的 array,然后从二进制文件中读取数据
17
floats2 = array("d")
18
fr = open("array.bin", "rb")
19
floats2.fromfile(fr, 10**7) # 读取的时候,指定读取多少个数据
20
fr.close()
21
print("the last number: " + str(floats2[-1]))
22
23
print(id(floats))
24
print(id(floats2))
25
print(floats == floats2)
26
27
"""
28
the last number: 0.40830065649386416
29
the last number: 0.40830065649386416
30
1547450711472
31
1547450138096
32
True
33
"""
Copied!

collections.deque

Python 内置的双端队列
1
from collections import deque
2
dq = deque(range(10), maxlen=10) # 初始化一个 双端队列,可以不给出 maxlen
3
print(dq) # deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)
4
5
# rotate(n) 当 n > 0 时,其功能为从 deque 的右边取出 n 个数,移动到左边,当 n<0时,其功能为从左边取出 -n 个数,移动到右边
6
dq.rotate(3)
7
print(dq) # deque([7, 8, 9, 0, 1, 2, 3, 4, 5, 6], maxlen=10)
8
dq.rotate(-4)
9
print(dq) # deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], maxlen=10)
10
11
# 从左端插入,append() 是默认右端插入
12
dq.appendleft(-1)
13
print(dq) # deque([-1, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)
14
# 默认从右端扩展
15
dq.extend([11,12,13,14])
16
print(dq) # deque([4, 5, 6, 7, 8, 9, 11, 12, 13, 14], maxlen=10)
17
18
# 从左端扩展,要注意的是,extendleft 是 iterate 的操作,所以插入后是逆序的
19
dq.extendleft([10,20,30,40])
20
print(dq) # deque([40, 30, 20, 10, 4, 5, 6, 7, 8, 9], maxlen=10)
21
22
# 双端弹出数据的操作,
23
print(dq.pop()) # 右端弹出数据
24
print(dq.popleft()) # 左端弹出数据
25
26
"""
27
deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)
28
deque([7, 8, 9, 0, 1, 2, 3, 4, 5, 6], maxlen=10)
29
deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], maxlen=10)
30
deque([-1, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)
31
deque([4, 5, 6, 7, 8, 9, 11, 12, 13, 14], maxlen=10)
32
deque([40, 30, 20, 10, 4, 5, 6, 7, 8, 9], maxlen=10)
33
9
34
40
35
"""
Copied!

operator

operator 通常用于 reduce, 详见 [functools.reduce()](#functools.reduce())

json

json module 用于处理 json 字符串和 json 文件。下面解释一下 json 包几个常见的方法:load()/dump()/loads()/dumps()
dumps(): 将 dict 转成 json 字符串, dumps2string
1
import json
2
data = {
3
'name' : 'ACME',
4
'shares' : 100,
5
'price' : 542.23
6
}
7
8
json_str = json.dumps(data)
9
# '{"price": 542.23, "name": "ACME", "shares": 100}'
Copied!
loads(): 将 json 字符串转成 dict, loads2dict
1
# 将 json 编码的字符串转换成一个 python 的数据结构,往往是 dict
Copied!
dump(), load(): 用于 读取 和 写入 json 文件。
1
# 如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据。
2
# Writing JSON data
3
with open('data.json', 'w') as f:
4
json.dump(data, f)
5
6
# Reading data back
7
with open('data.json', 'r') as f:
8
data = json.load(f)
Copied!

You May not Really Konw

strip()

strip() 方法并不是整个字符串进行前缀后缀的匹配,其更像是正则匹配的 [abcd] 规则。DOC
1
print('www.example.com'.strip('cmowz.'))
2
print('#....... Section 3.2.1 Issue #32 .......'.strip('.#! '))
3
4
"""
5
example
6
Section 3.2.1 Issue #32
7
"""
Copied!

else with for and while

如果 for 没有 break(sequence 遍历完毕),则执行 else,功能类似于 all(),是 all() 方法的复杂逻辑实现。
1
sentence = ["nihao", "woshi", "cxk"]
2
3
for word in sentence:
4
if word == "quit":
5
print("Time to quit")
6
break
7
else:
8
print("no quit")
9
else:
10
print("There was no 'quit' in the sentence")
11
12
"""
13
no quit
14
no quit
15
no quit
16
There was no 'quit' in the sentence
17
"""
18
19
###################################################
20
21
for i in range(10):
22
pass
23
else:
24
print("over")
25
# over
26
27
##################################################
28
29
for i in range(10):
30
if i == 3:
31
break
32
else:
33
print("over")
34
# 无 over
Copied!