1 字符串与编码
%d:整数
%f:浮点数
%s:字符串
%x:十六进制数
当%是一个普通字符的时候,用%%来表示%;
e.g
print("growth rate:%d %%" % 7)
result:growth rate: 7 %)
2 list(元素的数据类型可以不同)—可变列表,无序[]表示
func:
len(list)——-list长度
list[i]——list第i个元素;list[-i]——-list倒数第i个元素
list.append(str)——–往list中追加str至末尾
list.insert(i,str)———把str插入到i位置
list.pop(i)————-删除list中第i个数,不填则默认删除最后一个数据
list[i]=str———把dii个元素替换成str
3 tuple 元组—不可变列表,有序()表示
func:
len(tuple)——-tuple长度
tuple[i]——tuple第i个元素;tuple[-i]——-tuple倒数第i个元素
tuple.append(str)——–往tuple中追加str至末尾
4 条件语句
if<条件判断1>:
<执行1>
elif<条件判断2>:
<执行2>
else:
<执行3>
5 循环语句
1.for in 循环
for x in …
2.while循环
6 dict 字典
func:
dict[key]—dict里key对应的值
dict.get(key,code)—-获取key对应的值,没有则返回code
dict.pop(key)—-删除key和其对应的值
7 set 集合 (不重复)
func:
set.add(key)—-添加key到set中
set.remove(key)—–删除key
8 函数
定义:
def 函数名(参数):
结构体
注:参数多个时,必选参数在前,默认参数在后
定义可变个数的参数的函数:
def 函数名(*参数):
结构体
9 切片
eg. L[0:10]——>取list前10条数据,若0开始则可以省略0.即L[:10]
L[-10:]——>取list后10条数据
L[:10:2]——>前10个数每2个取一个
L[::5]——>所有数每5个取一个
(tuple也适用)
10 生成器
eg.杨辉三角
def tri():
L=[1]
while True:
yield (L)
L=[1]+[L[i]+L[i+1] for i in range(len(L)-1)]+[1]
n=0
for t in tri():
print(t)
n+=1
if n==2:
break
11 map/reduce
eg.将字符串转换成float
from functools import reduce
def str2float(s):
return reduce(lambda x, y: x + int2dec(y), map(str2int, s.split('.')))
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
def intLen(i):
return len('%d' % i)
def int2dec(i):
return i / (10 ** intLen(i))
print(str2float('1234.56'))
12 filter
eg. 回文数筛选
def is_huishu(n):
s=0
t=n
while n>0:
i=n%10
n=n//10
s=s*10+i
if s==t:
return True
else:
return False
output=filter(is_huishu,range(10000,100000))
print(list(output))