为了做机器学习项目,从零开始学习Python,本文重在新手快速入门,其中首选python科学计算环境——Anaconda,机器学习项目之前一般有3-4天快速学习新的语言时间,然后从项目中边做边学。下面是我结合结合结合一些Python入门相关书籍和资料做的笔记,希望对于新手有帮助。
下载地址:http://continuum.io/downloads
安装非常简单,安装完成后会看到Anaconda管理器(Anaconda Command Prompt),IPython Notebook,IPython QT,IPython,Spyder,下面是点开Spyder的界面:
在Anaconda管理器中输入conda list来查看已经安装的库,可以检查安装好了的NumPy,SciPy,Matplotlib,Pandas等库,非常方便
movies =["The Holy Grail",1975,"Terry Jone",91,
["Graham Chapman",
["Michael Palin","John Cleese"]
]
]
for each_item in movies:
print (each_item)
The Holy Grail
1975
Terry Jone
91
[‘Graham Chapman’, [‘Michael Palin’, ‘John Cleese’]]
for each_item in movies:
if(isinstance(each_item,list)): #isinstance内置函数(BIF)判断python类型
for nested_item in each_item:
print (nested_item)
else:
print(each_item)
The Holy Grail
1975
Terry Jone
91
Graham Chapman
['Michael Palin', 'John Cleese']
dir(__builtins__)
help(isinstance)
for nested_item in each_item:
if isinstance(nested_item,list):
for deeper_item in nested_item:
print(deeper_item)
else:
print (nested_item)
for each_item in the_list:
if isinstance(each_item,list):
print_lol(each_item)
else:
print(each_item)e Holy G1975
Terry Jone
91
Graham Chapman
Michael Palin
John Cleese
形式: [表达式 for 变量 in 列表] or [表达式 for 变量 in 列表 条件]
test1 =[1,2,3,4,5,6,7,8,9]
print [v*10 for v in test1 if v>4]
[50, 60, 70, 80, 90]
timesten = dict([(v,v*10) for v in test1])
#{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90}
timesten[2] #20
print [(i,j) for i in test1 if i>6 for j in range(3)]
#[(7, 0), (7, 1), (7, 2), (8, 0), (8, 1), (8, 2), (9, 0), (9, 1), (9, 2)]
matrix = [[0,1,2,3], [4,5,6,7], [8,9,10,11]]
flattened = []
for row in matrix:
for i in row:
flattened.append(i)
flattened = [i for row in matrix for i in row] #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
import os
files = []
for f in os.listdir('./.ropeproject'):
if f.endswith('.py'):
files.append(f)
files = [os.path.join('.\\.ropeproject', f) for f in os.listdir('.\\.ropeproject') if f.endswith('.py')]
lambda存在意义就是对简单函数的简洁表示,Python用lambda函数创建匿名函数
函数语法:lambda [arg1,[,arg2,….argn]] : expression
sum = lambda x, y : x + y
print(sum(2, 3)) # 5
L =[(lambda x : x**2),(lambda y:y**3),(lambda z:z**4)]
print L[0](2),L[1](3),L[2](4)
D ={'f1' : (lambda x : x**2),'f2':(lambda y:y**3)}
print D['f1'](1),D['f2'](2)
print [x**2 for x in range(10)]
print map((lambda x: x**2), range(10))
dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
for k,value in dict.items():
print k,value
def foo(*args):
numargs = len(args)
print "参数个数:{0}".format(numargs)
for i,x in enumerate(args):
print "Argument {0} is :{1}".format(i,x)
foo('I','engage','ML')
#参数个数:3
#Argument 0 is :I
#Argument 1 is :engage
#Argument 2 is :ML
参考资料: