Python 入门演示

简单的数学运算

整数相加,得到整数:

In [1]:

  1. 2 + 2

Out[1]:

  1. 4

浮点数相加,得到浮点数:

In [2]:

  1. 2.0 + 2.5

Out[2]:

  1. 4.5

整数和浮点数相加,得到浮点数:

In [3]:

  1. 2 + 2.5

Out[3]:

  1. 4.5

变量赋值

Python使用<变量名>=<表达式>的方式对变量进行赋值

In [4]:

  1. a = 0.2

字符串 String

字符串的生成,单引号与双引号是等价的:

In [5]:

  1. s = "hello world"
  2. s

Out[5]:

  1. 'hello world'

In [6]:

  1. s = 'hello world'
  2. s

Out[6]:

  1. 'hello world'

三引号用来输入包含多行文字的字符串:

In [7]:

  1. s = """hello
  2. world"""
  3. print s
  1. hello
  2. world

In [8]:

  1. s = '''hello
  2. world'''
  3. print s
  1. hello
  2. world

字符串的加法:

In [9]:

  1. s = "hello" + " world"
  2. s

Out[9]:

  1. 'hello world'

字符串索引:

In [10]:

  1. s[0]

Out[10]:

  1. 'h'

In [11]:

  1. s[-1]

Out[11]:

  1. 'd'

In [12]:

  1. s[0:5]

Out[12]:

  1. 'hello'

字符串的分割:

In [13]:

  1. s = "hello world"
  2. s.split()

Out[13]:

  1. ['hello', 'world']

查看字符串的长度:

In [14]:

  1. len(s)

Out[14]:

  1. 11

列表 List

Python用[]来生成列表

In [15]:

  1. a = [1, 2.0, 'hello', 5 + 1.0]
  2. a

Out[15]:

  1. [1, 2.0, 'hello', 6.0]

列表加法:

In [16]:

  1. a + a

Out[16]:

  1. [1, 2.0, 'hello', 6.0, 1, 2.0, 'hello', 6.0]

列表索引:

In [17]:

  1. a[1]

Out[17]:

  1. 2.0

列表长度:

In [18]:

  1. len(a)

Out[18]:

  1. 4

向列表中添加元素:

In [19]:

  1. a.append("world")
  2. a

Out[19]:

  1. [1, 2.0, 'hello', 6.0, 'world']

集合 Set

Python用{}来生成集合,集合中不含有相同元素。

In [20]:

  1. s = {2, 3, 4, 2}
  2. s

Out[20]:

  1. {2, 3, 4}

集合的长度:

In [21]:

  1. len(s)

Out[21]:

  1. 3

向集合中添加元素:

In [22]:

  1. s.add(1)
  2. s

Out[22]:

  1. {1, 2, 3, 4}

集合的交:

In [23]:

  1. a = {1, 2, 3, 4}
  2. b = {2, 3, 4, 5}
  3. a & b

Out[23]:

  1. {2, 3, 4}

并:

In [24]:

  1. a | b

Out[24]:

  1. {1, 2, 3, 4, 5}

差:

In [25]:

  1. a - b

Out[25]:

  1. {1}

对称差:

In [26]:

  1. a ^ b

Out[26]:

  1. {1, 5}

字典 Dictionary

Python用{key:value}来生成Dictionary。

In [27]:

  1. d = {'dogs':5, 'cats':4}
  2. d

Out[27]:

  1. {'cats': 4, 'dogs': 5}

字典的大小

In [28]:

  1. len(d)

Out[28]:

  1. 2

查看字典某个键对应的值:

In [29]:

  1. d["dogs"]

Out[29]:

  1. 5

修改键值:

In [30]:

  1. d["dogs"] = 2
  2. d

Out[30]:

  1. {'cats': 4, 'dogs': 2}

插入键值:

In [31]:

  1. d["pigs"] = 7
  2. d

Out[31]:

  1. {'cats': 4, 'dogs': 2, 'pigs': 7}

所有的键:

In [32]:

  1. d.keys()

Out[32]:

  1. ['cats', 'dogs', 'pigs']

所有的值:

In [33]:

  1. d.values()

Out[33]:

  1. [4, 2, 7]

所有的键值对:

In [34]:

  1. d.items()

Out[34]:

  1. [('cats', 4), ('dogs', 2), ('pigs', 7)]

数组 Numpy Arrays

需要先导入需要的包,Numpy数组可以进行很多列表不能进行的运算。

In [35]:

  1. from numpy import array
  2. a = array([1, 2, 3, 4])
  3. a

Out[35]:

  1. array([1, 2, 3, 4])

加法:

In [36]:

  1. a + 2

Out[36]:

  1. array([3, 4, 5, 6])

In [37]:

  1. a + a

Out[37]:

  1. array([2, 4, 6, 8])

画图 Plot

Python提供了一个很像MATLAB的绘图接口。

In [38]:

  1. %matplotlib inline
  2. from matplotlib.pyplot import plot
  3. plot(a, a**2)

Out[38]:

  1. [<matplotlib.lines.Line2D at 0x9fb6fd0>]

02.01 Python 入门演示 - 图1

循环 Loop

In [39]:

  1. line = '1 2 3 4 5'
  2. fields = line.split()
  3. fields

Out[39]:

  1. ['1', '2', '3', '4', '5']

In [40]:

  1. total = 0
  2. for field in fields:
  3. total += int(field)
  4. total

Out[40]:

  1. 15

Python中有一种叫做列表推导式(List comprehension)的用法:

In [41]:

  1. numbers = [int(field) for field in fields]
  2. numbers

Out[41]:

  1. [1, 2, 3, 4, 5]

In [42]:

  1. sum(numbers)

Out[42]:

  1. 15

写在一行:

In [43]:

  1. sum([int(field) for field in line.split()])

Out[43]:

  1. 15

文件操作 File IO

In [44]:

  1. cd ~
  1. d:\Users\lijin

写文件:

In [45]:

  1. f = open('data.txt', 'w')
  2. f.write('1 2 3 4\n')
  3. f.write('2 3 4 5\n')
  4. f.close()

读文件:

In [46]:

  1. f = open('data.txt')
  2. data = []
  3. for line in f:
  4. data.append([int(field) for field in line.split()])
  5. f.close()
  6. data

Out[46]:

  1. [[1, 2, 3, 4], [2, 3, 4, 5]]

In [47]:

  1. for row in data:
  2. print row
  1. [1, 2, 3, 4]
  2. [2, 3, 4, 5]

删除文件:

In [48]:

  1. import os
  2. os.remove('data.txt')

函数 Function

Python用关键词def来定义函数。

In [49]:

  1. def poly(x, a, b, c):
  2. y = a * x ** 2 + b * x + c
  3. return y
  4.  
  5. x = 1
  6. poly(x, 1, 2, 3)

Out[49]:

  1. 6

用Numpy数组做参数x:

In [50]:

  1. x = array([1, 2, 3])
  2. poly(x, 1, 2, 3)

Out[50]:

  1. array([ 6, 11, 18])

可以在定义时指定参数的默认值:

In [51]:

  1. from numpy import arange
  2.  
  3. def poly(x, a = 1, b = 2, c = 3):
  4. y = a*x**2 + b*x + c
  5. return y
  6.  
  7. x = arange(10)
  8. x
  9. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Out[51]:

  1. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [52]:

  1. poly(x)

Out[52]:

  1. array([ 3, 6, 11, 18, 27, 38, 51, 66, 83, 102])

In [53]:

  1. poly(x, b = 1)

Out[53]:

  1. array([ 3, 5, 9, 15, 23, 33, 45, 59, 75, 93])

模块 Module

Python中使用import关键词来导入模块。

In [54]:

  1. import os

当前进程号:

In [55]:

  1. os.getpid()

Out[55]:

  1. 4400

系统分隔符:

In [56]:

  1. os.sep

Out[56]:

  1. '\\'

- 类 Class

class来定义一个类。Person(object)表示继承自object类;init函数用来初始化对象;self表示对象自身,类似于C Java里面this

In [57]:

  1. class 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

构建新对象:

In [58]:

  1. person = Person('Mertle', 'Sedgewick', 52)

调用对象的属性:

In [59]:

  1. person.first

Out[59]:

  1. 'Mertle'

调用对象的方法:

In [60]:

  1. person.full_name()

Out[60]:

  1. 'Mertle Sedgewick'

修改对象的属性:

In [61]:

  1. person.last = 'Smith'

添加新属性,d是之前定义的字典:

In [62]:

  1. person.critters = d
  2. person.critters

Out[62]:

  1. {'cats': 4, 'dogs': 2, 'pigs': 7}

网络数据 Data from Web

In [63]:

  1. url = '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'

处理后就相当于一个可读文件:

In [64]:

  1. import urllib2
  2. ge_csv = urllib2.urlopen(url)
  3. data = []
  4. for line in ge_csv:
  5. data.append(line.split(','))
  6. data[:4]

Out[64]:

  1. [['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close\n'],
  2. ['2013-11-05', '26.32', '26.52', '26.26', '26.42', '24897500', '24.872115\n'],
  3. ['2013-11-04',
  4. '26.59',
  5. '26.59',
  6. '26.309999',
  7. '26.43',
  8. '28166100',
  9. '24.88153\n'],
  10. ['2013-11-01',
  11. '26.049999',
  12. '26.639999',
  13. '26.030001',
  14. '26.540001',
  15. '55634500',
  16. '24.985086\n']]

使用pandas处理数据:

In [65]:

  1. ge_csv = urllib2.urlopen(url)
  2. import pandas
  3. ge = pandas.read_csv(ge_csv, index_col=0, parse_dates=True)
  4. ge.plot(y='Adj Close')

Out[65]:

  1. <matplotlib.axes._subplots.AxesSubplot at 0xc2e3198>

02.01 Python 入门演示 - 图2

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/02-python-essentials/02.01-a-tour-of-python.ipynb