字符串
字符串索引与list相同。
#字符串的加法:
s = "hello" + " world"
=>
'hello world'
#查看字符串的长度:
len(s)
#字符串的分割:
s = "hello world"
s.split()
=>
['hello', 'world']
列表 List
#生成列表
a = [1, 2.0, 'hello', 5 + 1.0]
#列表加法:
a + a
=>
[1, 2.0, 'hello', 6.0, 1, 2.0, 'hello', 6.0]
#列表长度:
len(a)
#列表中添加元素:
a.append("world")
=>
[1, 2.0, 'hello', 6.0, 'world']
#append | extend
b=[6.2,'ted']
a.append(b)
=>
[1, 3.5, 'yes', 'no', [6.2, 'ted']]
a.extend(b)
=>
[1, 3.5, 'yes', 'no', 6.2, 'ted']
集合 Set
#生成集合,集合中不含有相同元素
s = {2, 3, 4, 2}
=>
{2, 3, 4}
#集合的长度:
len(s)
#向集合中添加元素:
s.add(1)
=>
{1, 2, 3, 4}
#集合的交:
a = {1, 2, 3, 4}
b = {2, 3, 4, 5}
a & b
=>
{2, 3, 4}
#并:
a | b
=>
{1, 2, 3, 4, 5}
#差:
a - b
{1}
#对称差:
a ^ b
=>
{1, 5}
字典 Dictionary
#用{key:value}生成Dictionary
d = {'dogs':5, 'cats':4}
=>
{'cats': 4, 'dogs': 5}
#字典的大小
len(d)
#增、改、查键值:
d["pigs"] = 7
d["dogs"] = 2
d["dogs"]
#所有的键:
d.keys()
#所有的值:
d.values()
#所有的键值对:
d.items()
=>
[('cats', 4), ('dogs', 2), ('pigs', 7)]
数组 Numpy Arrays
from numpy import array
a = array([1, 2, 3, 4])
#加法:
a + a
=>
array([2, 4, 6, 8])
画图 Plot
%matplotlib inline
from matplotlib.pyplot import plot
plot(a, a**2)
循环 Loop
line = '1 2 3 4 5'
fields = line.split()
fields
=>
['1', '2', '3', '4', '5']
total = 0
for field in fields:
total += int(field)
total
#列表推导式
numbers = [int(field) for field in fields]
sum(numbers)
文件操作 File IO
#写文件:
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
=>
[[1, 2, 3, 4], [2, 3, 4, 5]]
for row in data:
print row
=>
[1, 2, 3, 4]
[2, 3, 4, 5]
函数 Function
def poly(x, a, b=1, c):
y = a * x ** 2 + b * x + c
return y
x = array([1, 2, 3])
poly(x, 1, 2, 3)
=>
array([ 6, 11, 18])
当前进程号:
import os
os.getpid()
#系统分隔符:
os.sep
类 Class
用class来定义一个类。 Person(object)表示继承自object类; init函数用来初始化对象; self表示对象自身
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.critters = 'a'