02.01 Python 入门演示
Python 入门演示
简单的数学运算
整数相加,得到整数:
12 + 2
4
浮点数相加,得到浮点数:
12.0 + 2.5
4.5
整数和浮点数相加,得到浮点数:
12 + 2.5
4.5
变量赋值
Python使用<变量名>=<表达式>的方式对变量进行赋值
1a = 0.2
字符串 String
字符串的生成,单引号与双引号是等价的:
1s = "hello world"
2s
'hello world'
1s = 'hello world'
2s
'hello world'
三引号用来输入包含多行文字的字符串:
1s = """hello
2world"""
3print s
hello
world
1s = '''hello
2world'''
3print s
hello
world
字符串的加法:
1s = "hello" + " world"
2s
'hello world'
字符串索引:
1s[0]
'h'
1s[-1]
'd'
1s[0:5]
'hello'
字符串的分割:
1s = "hello world"
2s.split()
['hello', 'world']
查看字符串的长度:
1len(s)
11
列表 List
Python用[]来生成列表
1a = [1, 2.0, 'hello', 5 + 1.0]
2a
[1, 2.0, 'hello', 6.0]
列表加法:
1a + a
[1, 2.0, 'hello', 6.0, 1, 2.0, 'hello', 6.0]
列表索引:
1a[1]
2.0
列表长度:
1len(a)
4
向列表中添加元素:
1a.append("world")
2a
[1, 2.0, 'hello', 6.0, 'world']
集合 Set
Python用{}来生成集合,集合中不含有相同元素。
1s = {2, 3, 4, 2}
2s
{2, 3, 4}
集合的长度:
1len(s)
3
向集合中添加元素:
1s.add(1)
2s
{1, 2, 3, 4}
集合的交:
1a = {1, 2, 3, 4}
2b = {2, 3, 4, 5}
3a & b
{2, 3, 4}
并:
1a | b
{1, 2, 3, 4, 5}
差:
1a - b
{1}
对称差:
1a ^ b
{1, 5}
字典 Dictionary
Python用{key:value}来生成Dictionary。
1d = {'dogs':5, 'cats':4}
2d
{'cats': 4, 'dogs': 5}
字典的大小
1len(d)
2
查看字典某个键对应的值:
1d["dogs"]
5
修改键值:
1d["dogs"] = 2
2d
{'cats': 4, 'dogs': 2}
插入键值:
1d["pigs"] = 7
2d
{'cats': 4, 'dogs': 2, 'pigs': 7}
所有的键:
1d.keys()
['cats', 'dogs', 'pigs']
所有的值:
1d.values()
[4, 2, 7]
所有的键值对:
1d.items()
[('cats', 4), ('dogs', 2), ('pigs', 7)]
数组 Numpy Arrays
需要先导入需要的包,Numpy数组可以进行很多列表不能进行的运算。
1from numpy import array
2a = array([1, 2, 3, 4])
3a
array([1, 2, 3, 4])
加法:
1a + 2
array([3, 4, 5, 6])
1a + a
array([2, 4, 6, 8])
画图 Plot
Python提供了一个很像MATLAB的绘图接口。
1%matplotlib inline
2from matplotlib.pyplot import plot
3plot(a, a**2)
[<matplotlib.lines.Line2D at 0x9fb6fd0>]
循环 Loop
1line = '1 2 3 4 5'
2fields = line.split()
3fields
['1', '2', '3', '4', '5']
1total = 0
2for field in fields:
3 total += int(field)
4total
15
Python中有一种叫做列表推导式(List comprehension)的用法:
1numbers = [int(field) for field in fields]
2numbers
[1, 2, 3, 4, 5]
1sum(numbers)
15
写在一行:
1sum([int(field) for field in line.split()])
15
文件操作 File IO
1cd ~
d:\Users\lijin
写文件:
1f = open('data.txt', 'w')
2f.write('1 2 3 4\n')
3f.write('2 3 4 5\n')
4f.close()
读文件:
1f = open('data.txt')
2data = []
3for line in f:
4 data.append([int(field) for field in line.split()])
5f.close()
6data
[[1, 2, 3, 4], [2, 3, 4, 5]]
1for row in data:
2 print row
[1, 2, 3, 4]
[2, 3, 4, 5]
删除文件:
1import os
2os.remove('data.txt')
函数 Function
Python用关键词def来定义函数。
1def poly(x, a, b, c):
2 y = a * x ** 2 + b * x + c
3 return y
4
5x = 1
6poly(x, 1, 2, 3)
6
用Numpy数组做参数x:
1x = array([1, 2, 3])
2poly(x, 1, 2, 3)
array([ 6, 11, 18])
可以在定义时指定参数的默认值:
1from numpy import arange
2
3def poly(x, a = 1, b = 2, c = 3):
4 y = a*x**2 + b*x + c
5 return y
6
7x = arange(10)
8x
9array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
1poly(x)
array([ 3, 6, 11, 18, 27, 38, 51, 66, 83, 102])
1poly(x, b = 1)
array([ 3, 5, 9, 15, 23, 33, 45, 59, 75, 93])
模块 Module
Python中使用import关键词来导入模块。
1import os
当前进程号:
1os.getpid()
4400
系统分隔符:
1os.sep
'\\'
- 类 Class
用class来定义一个类。
Person(object)表示继承自object类;
__init__函数用来初始化对象;
self表示对象自身,类似于C Java里面this。
1class Person(object):
2 def __init__(self, first, last, age):
3 self.first = first
4 self.last = last
5 self.age = age
6 def full_name(self):
7 return self.first + ' ' + self.last
构建新对象:
1person = Person('Mertle', 'Sedgewick', 52)
调用对象的属性:
1person.first
'Mertle'
调用对象的方法:
1person.full_name()
'Mertle Sedgewick'
修改对象的属性:
1person.last = 'Smith'
添加新属性,d是之前定义的字典:
1person.critters = d
2person.critters
{'cats': 4, 'dogs': 2, 'pigs': 7}
网络数据 Data from Web
1url = 'http://ichart.finance.yahoo.com/table.csv?s=GE&d=10&e=5&f=2013&g=d&a=0&b=2&c=1962&ignore=.csv'
处理后就相当于一个可读文件:
1import urllib2
2ge_csv = urllib2.urlopen(url)
3data = []
4for line in ge_csv:
5 data.append(line.split(','))
6data[:4]
[['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close\n'],
['2013-11-05', '26.32', '26.52', '26.26', '26.42', '24897500', '24.872115\n'],
['2013-11-04',
'26.59',
'26.59',
'26.309999',
'26.43',
'28166100',
'24.88153\n'],
['2013-11-01',
'26.049999',
'26.639999',
'26.030001',
'26.540001',
'55634500',
'24.985086\n']]
使用pandas处理数据:
1ge_csv = urllib2.urlopen(url)
2import pandas
3ge = pandas.read_csv(ge_csv, index_col=0, parse_dates=True)
4ge.plot(y='Adj Close')
<matplotlib.axes._subplots.AxesSubplot at 0xc2e3198>