Python 入门演示
简单的数学运算
整数相加,得到整数:
2 + 2
浮点数相加,得到浮点数:
2.0 + 2.5
整数和浮点数相加,得到浮点数:
2 + 2.5
变量赋值
Python使用<变量名>=<表达式>的方式对变量进行赋值
a = 0.2
字符串 String
字符串的生成,单引号与双引号是等价的:
s = "hello world"
s
s = 'hello world'
s
三引号用来输入包含多行文字的字符串:
s = """hello
world"""
print (s)
s = '''hello
world'''
print (s)
字符串的加法:
s = "hello" + " world"
s
字符串索引:
s[0]
s[-1]
s[0:5]
字符串的分割:
s = "hello world"
s.split()
查看字符串的长度:
len(s)
列表 List
Python用[]来生成列表
a = [1, 2.0, 'hello', 5 + 1.0]
a
列表加法:
a + a
列表索引:
a[1]
列表长度:
len(a)
向列表中添加元素:
a.append("world")
a
集合 Set
Python用{}来生成集合,集合中不含有相同元素。
s = {2, 3, 4, 2}
s
集合的长度:
len(s)
向集合中添加元素:
s.add(1)
s
集合的交:
a = {1, 2, 3, 4}
b = {2, 3, 4, 5}
a & b
并:
a | b
差:
a - b
对称差:
a ^ b
字典 Dictionary
Python用{key:value}来生成Dictionary。
d = {'dogs':5, 'cats':4}
d
字典的大小
len(d)
查看字典某个键对应的值:
d["dogs"]
修改键值:
d["dogs"] = 2
d
插入键值:
d["pigs"] = 7
d
所有的键:
d.keys()
所有的值:
d.values()
所有的键值对:
d.items()
数组 Numpy Arrays
需要先导入需要的包,Numpy数组可以进行很多列表不能进行的运算。
from numpy import array
a = array([1, 2, 3, 4])
a
加法:
a + 2
a + a
画图 Plot
Python提供了一个很像MATLAB的绘图接口。
%matplotlib inline
from matplotlib.pyplot import plot
plot(a, a**2)
循环 Loop
line = '1 2 3 4 5'
fields = line.split()
fields
total = 0
for field in fields:
total += int(field)
total
Python中有一种叫做列表推导式(List comprehension)的用法:
numbers = [int(field) for field in fields]
numbers
sum(numbers)
写在一行:
sum([int(field) for field in line.split()])
文件操作 File IO
cd ./
写文件:
f = open('data.txt', 'w')
f.write('1 2 3 4\n')
f.write('2 3 4 5\n')
f.close()
读文件:
f = open('data.txt')
data = []
for line in f:
data.append([int(field) for field in line.split()])
f.close()
data
for row in data:
print (row)
删除文件:
import os
os.remove('data.txt')
函数 Function
Python用关键词def来定义函数。
def poly(x, a, b, c):
y = a * x ** 2 + b * x + c
return y
x = 1
poly(x, 1, 2, 3)
用Numpy数组做参数x:
x = array([1, 2, 3])
poly(x, 1, 2, 3)
可以在定义时指定参数的默认值:
from numpy import arange
def poly(x, a = 1, b = 2, c = 3):
y = a*x**2 + b*x + c
return y
x = arange(10)
x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
poly(x)
poly(x, b = 1)
模块 Module
Python中使用import关键词来导入模块。
import os
当前进程号:
os.getpid()
系统分隔符:
os.sep
- 类 Class
用class来定义一个类。
Person(object)表示继承自object类;
__init__函数用来初始化对象;
self表示对象自身,类似于C Java里面this。
class Person(object):
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
def full_name(self):
return self.first + ' ' + self.last
构建新对象:
person = Person('Mertle', 'Sedgewick', 52)
调用对象的属性:
person.first
调用对象的方法:
person.full_name()
修改对象的属性:
person.last = 'Smith'
添加新属性,d是之前定义的字典:
person.critters = d
person.critters
网络数据 Data from Web
url = 'http://www.sample-videos.com/csv/Sample-Spreadsheet-10-rows.csv'
处理后就相当于一个可读文件:
import urllib.request
aa = urllib.request.urlopen(url)
ge_csv = aa.read()
data = []
for line in ge_csv:
data.append(line)
data[:4]
