Python Notes

Updated on Jan 16, 2019

1 Syntax

1.1 格式化输出

>>> no = 74
>>> year = 1984
>>> s = "Soldier %04d, welcome to %d." % (no, year)
>>> s
'Soldier 0074, welcome to 1984.'
# d代表十进制数据,4是最小输出字符数,用0填充。

1.2 对象复制

int , str 数据类型可以直接使用 =

>>> s1 = "nice"
>>> s2 = s1
>>> s1 += " tits"
>>> s2 += " boobs"
>>> s1
'nice tits'
>>> s2
'nice boobs'

list 数据类型则不能使用 =,要使用 copy 模块

import copy
# 一维数组可以使用list()或copy()
a = [1, 2, 3]
b = list(a)
b = copy.copy(a)
# 高维数组必须使用deepcopy()
a = [[1, 2], [3, 4]]
b = copy.deepcopy(a)

1.3 fun with True & 1

>>> type(True)
<class 'bool'>
>>> type(1)
<class 'int'>
>>> 1 == True
True
>>> 1 ^ True
0
>>> 0 ^ True
1

1.4 list sort

list 进行排序

>>> li = [[2, 6.6], [4, 5]]
>>> li.sort(key=lambda e:e[1])
>>> li
[[4, 5], [2, 6.6]]
>>> li.sort(key=lambda e:e[1], reverse=True)
>>> li
[[2, 6.6], [4, 5]]
# sort 默认升序排序,reverse 逆序

1.5 iterate through tow list

同步遍历两个 list

>>> la = [1, 2, 3, 4]
>>> lb = ['a', 'b', 'c']
>>> for e1, e2 in zip(la, lb):
...     print(e1, e2)
1 a
2 b
3 c

1.5 inf

Python 中的无穷小与无穷大

>>> float('-inf') < -999
True
>>> 999 < float('inf')
True
>>> float('-inf') == float('inf')
False

2 IO

2.1 读写文本文件

li = ["The Beatles", "David Bowie", "Radiohead", "Blur"]
# write
with open("1.txt", "w") as fp:
	for e in li:
		print(e)
		fp.write(e + "\n")
        
# read
with open("1.txt", "r") as fp:
    lines = fp.readlines()
for line in lines:
    print(line.split())

2.2 文件批处理三连

import os
import shutil
    
dirname = os.getcwd()
filenamelist = os.listdir(dirname)
i = 0
for name in filenamelist:
    if name[-4:] == ".jpg":
    	print(name)
        os.remove(name, str(i) + ".jpg")
        os.remove(name)
    	shutil.move(name,"./small/") 
        i += 1

3 etc.

3.1 Execute

Python脚本可以在终端直接运行

python xxx.py

Python某些内置的模块(如SimpleHTTPServer)也能够以脚本方式直接运行,需添加参数-m。

python -m SimpleHTTPServer

3.2 生成随机01比特串

不限定01比例

# A 使用 numpy
import numpy as np
li = np.random.randint(0,2,5)
# B 使用 random.sample
import random
li = [0, 1] * 10
li = random.sample(li, 3)

限定01比例

# 使用 random.shuffle
import random
l0 = [0] * 2
l1 = [1] * 4
li = l0 + l1
random.shuffle(li) 

4 TBC

ゴールド・エクスペリエンス!