规范学习python,以为后续的机器学习奠定基础
from random import randint
data = [randint(-10,10) for _ in range(10)]
for i in ( filter(lambda x : x >=0,data)):
print(i)
[x for x in data if x>=0]
from random import randint
dict = {x :randint(60,100)for x in range(1,21)}
{k:v for k,v in dict.items() if v>90 }
from random import randint
s = set ( [ randint(-10,10) for _ in range(10)] )
{x for x in s if x>0}
数据结构固定,用元组。但是index访问元组内容,十分不便。
student = ('Jax',20,'male','201764681188')
NAME,AGE,SEX = 0,1,2
student[NAME]
from collections import namedtuple
Student = namedtuple('Student',['name','age','male','ID'])
s = Student('jax',16,'m','2017')
s.name
data = [ randint(0,20) for _ in range(30)]
ans = dict.fromkeys(data,0)
ans = dict.fromkeys(data,0)
for x in data:
ans[x]+=1
c2 = Counter(data)
c2.most_comment(3)
from random import randint
dict = {x:randint(60,100) for x in 'xyzabc'}
sorted(zip(dict.values(),dict.keys()))
sorted(dict.items(),key = lambda x : x[1])
round1 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))}
round2 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))}
round3 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))}
round1.keys()&round2.keys()&round3.keys()
from collections import OrderedDict
d = OrderedDict()
d[key] = value;
from collections import deque
q = deque([],queueSize)
q.apend(record)
保存
import pickle
pickle.dump(q,open('history','w'))
读取
q2 = pickle.load(open('history'))
由可迭代对象(list,string)得到迭代器对象 iter()
skip
class PrimeNumbers:
def __init__(self,start,end):
self.start = start
self.end = end
def isPrimeNum(self,k):
if k<2:
return False
for i in range(2,k):
if k%i == 0:
return False
return True
#实现__iter__接口,让PrimeNumbers可迭代
def __iter__(self):
for k in range(self.start,self.end+1):
if self.isPrimeNum(k):
yield k
测试程序
for x in PrimeNumbers(1,100):
print(x)
from collections import Iterable,Iterator
l = [1,2,3,4,5]
#正向
for x in iter(l):
print(x)
#反向
for x in reversed(l):
print(x)
事实上,正向迭代需要实现接口__init__() ,反向迭代需要实现接口__reversed__()
浮点数生成器
class FloatRange:
def __init__(self,start,end,step=0.1):
self.start = start
self.end = end
self.step = step
def __iter__(self):
t = self.start
while t <= self.end:
yield t
t +=self.step
def __reversed__(self):
t = self.end
while t >= self.start:
yield t
t -=self.step
for i in FloatRange(1.0,4.0,0.5):
print(i)
print('-'*6)
for i in reversed( FloatRange(1.0,4.0,0.5) ):
print(i)
#islice会对原对象f造成影响
from itertools import islice
#f为可迭代对象,末尾用none表示
for line in islice(f,100,300):
print(line)
#zip中包装,for中拆分
for c,m,e in zip(chinese,math,english):
print(...)
for x in chain([1,2,3,4],[5,6,7]):
print(...)
用string.split只能含有一个分隔符的情况
s = "abc,ef;gi"
import re
print(re.split(r'[,;]+',s))
''.join(['abc','123','45'])
#如果join的内容除了有字符串,还有数字什么的
list = ['abc',123,45]
''.join(str(x) for x in list)
'abc'.ljust(20)
#去掉两端空白
s = ' abc\t\r 123 '
s.strip()
#s = '---abc 123+++'
#s.strip(r'-+')
#切片拼接
s[:3]+s[5:]
#replace
s.replace(' ','')
#使用re.sub
import re
re.sub('[\t\r]','',s)
import csv
rf = open('1.csv','rb')
#reader就是1.csv的迭代器了
reader = csv.rader(rf)
wf = open('2.csv','wb')
writer = csv.writer(wf)
weiter.writerow(...)
#python->jason
l = ['1','2',"abc"]
j1 = json.dumps(l)
#jason->python
l2 = jason.loads(j1)