python memo

@see python程式設計入門 -葉難

基本

保留字

and as assert break class continue def del elif else except exec finally for from global if import in is lambda nonlocal not or pass print raise return try while with yield None False True

弱型態

可以是int,long,float,str,bool,list,tuple。都是object。

強制指定型態

int(3)
long(123L)
float(3.14)
str(‘aaa’),str(3.14),str([1,2,3]),str([]),str(()),str(True),str()
bool(True),bool([]),bool(()),bool(‘’),bool(0),bool(0.0),bool(None)
list([0,1,2,3,4,’a’,’b’])
tuple((0,1,2,3,4,’a’,’b’))

字串用’或”都可以, 預設用’

以換行做為statement結尾。也可用分號結尾,合並多個statement。

list

從0開始
內容不需是同一種型態
list=[0,1,2,3,4,5,6]
list=[‘frank’,111,3222,[‘c’,’python’]]
list
list[0]
list[3]
list[3][1]
list[1]*list[2]
list[1]=999
list[1]
s=”wijefiwjeifj”
s=’iiu2iu3i5u3iu’
s

tuple; immutable list

()
t=(0,1,2,3,4,5,6,7)
t[0]
t=(‘zero’,1,2,22.33,’kk’,(‘final’,”FINAL”))
t[5]
t[5][1]

tuple注意事項

t[1]=333 #you got error to assign value on tuple
oneElementStr=(‘juststr not tuple’)
oneElementStr
oneElementTuple=(‘only1’ ,) #need comma in the end
oneElementTuple
t3=’asdfw’,’aaa’,’vvvv’ #simplify expression of tuple
t3

operator +-*/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
% 除法只取餘數
// 除法只取商
** 次方

>>> 17/3
5
>>> 17.0/3.0
5.666666666666667
>>>

>>> 'hello'+ ' '+ 'world' +'!'
'hello world!'
>>> 'hello'*3
'hellohellohello'
>>> [1,2,3]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> [1,2,3]+['a','b','c']
[1, 2, 3, 'a', 'b', 'c']

comparison operator < <= > >= != <> ==

in, not in for list/tuple

is, is not for reference check

logical comparator and, or, not

boolean True, False

False == () #False
False == [] #False
False == [‘0’] #False
False == [0] #False
False == (0,) #False
False == ‘0’ #False
False == 0 #True

False

False
None
0
‘’
[]
()

True

not False
‘0’
[0]
(0,)

assignment

a=b=c=3
b=4;c=5
x=y=z=[0,1,2,3,4]
x,y,z #自動組成tuple

serial assignment

(a,b,c)=(0,1,2)
a;b;c;
a,b,c=0,1,2
a,b=b,a #exchange a,b
a;b;c;
[a,b,c]=[9,8,7] #list或tuple寫法都可以
a;b;c;

star mark for only python3

x=[0,1,2,3,4,5]
a,*b,c=x
a,b,c #等於(0,[1,2,3,4],5)

+= -= = /= %= //= *= >>= <<= &= ^= |=

if/elif/else 使用:和tab做區塊包圍檢查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
a,b,c=1,2,3
x=None;
if a<b:
if b<c:
x=c
else:
x=b
else:
if a<c:
x=c
else:
x=a
#多一個換行結束if操作

x
print x
print(x)
1
2
3
4
5
a,b,c=0,'',[]
if a and b and c:
print('all true')
else:
pass #do nothing for avoid error in else statement

while

1
2
3
4
5
6
i=1;x=0;
while i<100:
x+=i
i+=1

i,x

for

1
2
3
4
5
6
7
8
9
scores=[23,54,52,55,99]
total=0
n=0
for x in scores:
n+=1
total+=x

avg=total/n
avg,total,n
for char in str
1
2
3
4
5
6
7
s='hello world'
count=0
for x in s:
if x=='e':
count+=1

count
serial assignment for list/tuple in for
1
2
3
4
5
6
7
nameScores=(('banana',32,55),('apple',67,48),('orange',72,8)) #list/tuple都可以
highs=[]
for x,y,z in nameScores:
if y>30 and z>40:
highs+=[x,y,z]

highs

break/continue for while/for

function; def/return

1
2
3
def testfunction(param):
return 0
#多一個換行結束if操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def sum(numbers,initial):
total=initial
for x in numbers:
total+=x
return total

sum((1,2,34,6,7),0)
sum([1,2,34,6,7],100)

#test return list/tuple
def avg(scores,initial=0):
n=0;total=initial;
for x in scores:
total +=x
n+=1
return (total,total/n)
#return total,total/n也行

avg((1,2,34,6,7))
avg([1,2,34,6,7],100)

scope: del, global

del強制變數gc
global在函數內強制使用全域變數

1
2
3
4
5
6
7
8
a=10 #什麼數值都無所謂
#del a #讓a變成未定義也不影響後面的global操作
def foo(n):
global a
a=100
return n+a

foo(5),a #105,100

內建函式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
a=[0,1,2,3,4]
len(a)
sum(a) #python2.x必需用 sum(a,0)
sum(a,1000)
max(a),min(a)
abs(3),abs(-3),abs(-3.14159)
pow(2,5)
pow(333,0),pow(0,0)
pow(2,5,3) #2^5%3
round(3.14159265358979323846,2) #四捨五入到小數第二位
round(3.14159265358979323846) #四捨五入到小數第0位
divmod(123,11) #商,餘
divmod(123.2389,11) #商,餘 float操作也OK

all(([0,1],'aaa',True,3)) #True
all(([],'',False,0)) #False
all(([],'',False,0,4)) #False

any(([0,1],'aaa',True,3)) #True
any(([],'',False,0)) #False
any(([],'',False,0,4)) #True

a=1234
def f():pass

id(a) #uid
type(a),type(f) #type
callable(a),callable(f)


range(10) #從0到param-1的list
range(5,10) #從5到param-1的list
range(5,10,2) #從5到param-1的list, step=2
range(5,-12,-4) #向負數跳也OK

for i in range(len(a)): #i是索引值
a[i]=a[i]+100

a

a=3
print a,a,a

a=raw_input() #python2.x的console input, python3.x用input()
a
#python2.x版的input()等同於eval(raw_input())

module

寫mymodule.py檔,其中可定義變數/函式

1
2
3
4
5
6
7
import mymodule #這就可以引入mymodule.py裡定義的一切
x=mymodule.functionA(1,2,3,4)
y=mymodule.valueB
`````` bash
import mymodule as mm#這就可以引入mymodule.py裡定義的一切, module name改用alias name使用
x=mm.functionA(1,2,3,4)
y=mm.valueB

1
2
3
from mymodule import * #引入一切,使用時不需要加上mymodule.
x=.functionA(1,2,3,4)
y=valueB
1
2
3
from mymodule import functionA #引入一切,使用時只有指定的import功能不需要加上mymodule.
x=functionA(1,2,3,4)
y=mymodule.valueB

standard module

builtins
dir(builtins)
keyword
iskeyword
math
pi e log10 log sqrt sin ceil floor trunc …
random
seed random randint uniform shuffle choice …
sys
path
maxint
-sys.maxint-1

module name

name
future

python file name

.py
.py3
.pyc
.pyo

file encoding

-- encoding: utf-8 --
-- encoding: big5 --
-- encoding: ascii --
-- encoding: iso-8859-1 --

as script file

!/usr/bin/python

chmod +x ./hello.py
./hello.py

List Comprehensions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
>>> S = [x**2 for x in range(10)]
>>> V = [2**i for i in range(13)]
>>> M = [x for x in S if x % 2 == 0]
>>> S;V;M;
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
[0, 4, 16, 36, 64]
>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
>>> primes = [x for x in range(2, 50) if x not in noprimes]
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> words = 'The quick brown fox jumps over the lazy dog'.split()
>>> words
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
>>> stuff = [[w.upper(), w.lower(), len(w)] for w in words]
>>> for i in stuff:
... print i
...
['THE', 'the', 3]
['QUICK', 'quick', 5]
['BROWN', 'brown', 5]
['FOX', 'fox', 3]
['JUMPS', 'jumps', 5]
['OVER', 'over', 4]
['THE', 'the', 3]
['LAZY', 'lazy', 4]
['DOG', 'dog', 3]
>>> stuff = map(lambda w: [w.upper(), w.lower(), len(w)], words)
>>> for i in stuff:
... print i
...
['THE', 'the', 3]
['QUICK', 'quick', 5]
['BROWN', 'brown', 5]
['FOX', 'fox', 3]
['JUMPS', 'jumps', 5]
['OVER', 'over', 4]
['THE', 'the', 3]
['LAZY', 'lazy', 4]
['DOG', 'dog', 3]

數值型別

#

0b1101,0xaa,0o1234
bin(100),hex(100),oct(100)
11111111111111111L #凡超過int最大值的數都自動轉成無窮精確度的long型別
1e6
314159e-5
314159E-5
float(‘nan’),float(‘inf’),float(‘-inf’)
import math
math.isnan(float(‘nan’))
math.isinf(float(‘inf’))
math.isfinite(float(‘inf’)),math.isfinite(float(‘nan’)) #only python3.x

三元運算

x,y,z=1,2,3
x if y>0 else z
1
(x>0 and x) or z #等效三元運算
1
d=100;n=None
a=d if n==None else n
b=(n==None) and d or n
b1=(n==None and d) or n
b2= n==None and d or n
c=(n and d ) or n
a,b,b1,b2,c
(100, 100, 100, 100, None)

operator from/to function

list=[0,1,2]
list.len()
3
list.append(3)
list
[0, 1, 2, 3]

x=’good’;y=’bye’
x+y
‘goodbye’
x.add(y)
‘goodbye’
x=3;y=4
x+y
7
x.add(y)
7
x.add(y).sub(y.pow(2))
-9

type complex

type(complex())
complex(1)
complex(1,2)
complex(1+2j,3+4j)
complex(‘5-6j’)
complex(‘5 - 6j’) #error
complex()

z=4+5j;z
z.real #實部
z.imag #虛部
z==z.real+z.imag*1j
z.conjugate() #共軛複數

+ - / * pow abs == !=
座標系轉換

import cmath
abs(x) #絕對值;模
cmath.phase(x) #輻角;弧度
ct=cmath.polar(x) #模和輻角的tuple
cmath.rect(ct[0],ct[1]) #以模和輻角建立complex
cmath.sqrt(-1) #負數的平方根

#

import cmath
exp log log10 acos asin acosh asinh …

轉型

str()
repr()

十進位 Decimal

from decimal import *
Decimal
Decimal(0.1), Decimal(3.14)
Decimal(‘0.1’), Decimal(‘3.14’)
D=Decimal
a=D(‘2.33’);b=D(‘4.82’)
a+b

分數 Fraction

from fractions import
Fraction
Fraction(1,3) #1/3
F=Fraction
F(‘-1/3’)
a,b,c=F(‘1/3’),F(‘11/3’),F(‘5/12’)
a+b,b-c,c
a,a/b
abs(a-b),round(b)
gcd(64,48) #最大公因數

位元運算 ~ << >> & ^ |

#

callable()
isinstance(x , types.FunctionType)
isinstance(x, tuple)
dir()
dir(int)
dir(list)
a=3,list=[0,1,2,3]
a.class, list__class
type(a),type(list)

namespace

local enclosing global builtin

Sized, Container, Sequence, MutableSequence, Iterable, Iterator

list=[0, 1, 2, 3]
lit=iter(list)
lit


next(lit)
0
next(lit)
1
next(lit)
2
next(lit)
3
next(lit)
Traceback (most recent call last):
File ““, line 1, in
StopIteration

index, slice
is, is not, ==, !=, in, not in, +, , +=, =
len min max sum iter next slice range xrange reversed sorted zip enumerate
index count append del extend insert pop reverse sort copy deepcopy

#

list=[33,44,55]
itr=iter(list)
while True:
try:
x=next(itr)
print(x)
except StopIteration:
break

n=0
for i in list:
n+=i;i,n

n=0
for i in iter(list):
n+=i;i,n

n=0
for i in range(1,10+1):
n+=i;i,n

n=0
for i,v in enumerate(list):
i,v

ii=[3,2,1]
for i,v in zip(ii,list):
i,v

data=zip(ii,list)
sorted(data)
data

def k(x):return x[1];

sorted(data,key=k)

list comprehension

list=[0,1,2,3,4,5]
[x*x for x in list]

[str(x)+’‘+str(y)+’=’+str(xy) for x in range(2,9+1) for y in range(1,9+1)] #九九乘法

li0=[‘a’,’b’,’c’]
li1=[‘.jpg’,’.png’,’.bmp’]
[x+y for x in li0 if x!=’a’ for y in li1 if y!=’.jpg’]

string

\’
\”
\
\n
\r
\t #HT; tab
\v #VT
\a #bell
\b #backspace
\f #page
\xff #hex
\ooo #oct

‘’’附號用來合併多行

s=’’’abc def
ghi kkl mno
pqr\t\nstu
vwxyz’’’
s

raw r或R都可以

r’\‘
R’\‘
r’\”‘
R’\”‘

\標示下一行繼續

s=’abc\
def\
hij’
s

dict

d={}
d={‘name’:’John’,’name’:27} #同key會被取代
d={‘name’:’John’,’age’:27,’list’:[3,4,5]}
d[‘name’]
type(d)
dict(d)
type(dict(d))
keys=[‘name’,’age’,’job’]
values=[‘john’,33,’programmer’]
d2=dict(zip(keys,values));d2

d={‘a’:1,’b’:2,’c’:3}
for k in d:
k

for k in d.keys():
k

for v in d.values():
v

for k,v in d.items():
k,v

len del get setdefault keys values items

set

x={1,2,3,4,4,4,4};x
set(x);
set({1,2,3234,234,1,1,1,1})
set([2,3,2,2,2,2,2])