python入门笔记

Jython

Jython是运行在Java平台上的Python解释器,可以直接把Python代码编译成Java字节码执行。

list

list=[]
len() //长度
list[i || -i] //访问元素
list.append(‘xxx’) //添加到末尾
classmates.insert(i, ‘xxx’) //添加到i
list.pop(i) //删除第i
list.replace(‘x’,’y’)

1
2
[x * x for x in range(1, 11) if x % 2 == 0] //[4, 16, 36, 64, 100]
[m + n for m in 'ABC' for n in 'XYZ'] //['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

tuple

tuple=(1,) //一个元素

if

1
2
3
4
5
6
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum) //while的循环

if //内部条件
break //跳出
continue //跳过

dict

d=[“xxx”:v] //字典定义
‘xxx’ in d //判断key存在

set

s = set([])
s.add
s.remove

def

def xxx():
tab

1
2
3
4
5
6
7
8
9
10
def add_end(L=None):
if L **is** None:
L = []
L.append('END')
return L //一个不变的调用函数

def fact(n):
if n==1:
return 1
return n * fact(n - 1) //一个递归

generator

1
2
3
4
5
6
7
8
g=(~~~)

def xxx ()
yield x

next(g)

for n in g(i) //生成前i个

map

1
2
3
4
5
6
def f(x):
return x * x

r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]

filter

1
2
3
4
5
def is_odd(n):
return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
//结果: [1, 5, 9, 15]

notname def

f = lambda x: x * x

装饰器 偏函数

@@@@@@@@@@@@@@@@@@

class

1
2
3
4
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
1
2
3
4
5
6
7
8
9
10
11
class Student(object):
...

def get_grade(self):
if self.score >= 90:
return 'A'
elif self.score >= 60:
return 'B'
else:
return 'C'
//类的方法定义

_xxx 视为私有
__xxx 私有
__xxx__ 特殊变量

try

1
2
3
4
5
6
7
8
9
10
11
try:
print('try...')
r = 10 / 0
print('result:', r)
except ZeroDivisionError as e:
print('except:', e)
else
xxxxxxxxxxxx
finally:
print('finally...')
print('END')