[ Applied Data Science with Python]week1
Functions
- 在Python中,你可以设置参数的预设值。例子中,我们可以重写add_numbers函数来接受三个参数, 但我们可以设最后的参数为预设的None 这意味着你可以使用两个值或三个值来调用add_numbers,而不必重写函数来重载(Overloading)它。
- 这里有一个重要的暗示含义。所有可选用的参数,那些有预设值的, 都需要放在函数声明的最末尾。这也意味着你可以传递可选参数为一个标记值。以下是有标记参数的例子。
def add_numbers(x,y,z=None):
if (z==None):
return x+y
else:
return x+y+z
print(add_numbers(1, 2))
print(add_numbers(1, 2, 3))
输出:
3
6
Types and Sequences
Types
str、NoneType、int、float、function等类型
字符串
- 格式化
sales_record = {
'price': 3.24,
'num_items': 4,
'person': 'Chris'}
sales_statement = '{} bought {} item(s) at a price of {} each for a total of {}'
print(sales_statement.format(sales_record['person'],
sales_record['num_items'],
sales_record['price'],
sales_record['num_items']*sales_record['price']))
Sequences
- Tuple(不可变) s=(x)
- List(可变) s=[x]
- Dictionary(可变) s={k:v}
通用序列的操作
s1+s2 | 拼接s1和s2 |
---|---|
s*n | 相对于s自身进行n次拼接 |
x in s | 元素x在s内,返回True;否则False |
x not in s | 元素x在s内,返回False;否则True |
s[i] | i为正数时,返回第i+1个元素,起始为0;i为负数时,返回倒数第|i|个元素 |
s[i:j] | 切片操作,从第i+1元素开始,到第j个元素停止,总数=j-i |
s[i:] | 返回从第i+1个元素开始到结尾之间的所有元素 |
s[:i] | 返回从开始到第i个元素之间的所有元素 |
len(s) | 返回s的长度 |
min(s) | 返回s的最小项 |
max | 返回s的最大项 |
s.index(x) | 返回x的索引 |
s.count(x) | 返回x出现的次数 |
Tuple的操作
-
Tuple 固定数组
-
Tuple 是不可变 list,一旦创建了一个 tuple 就不能以任何方式改变它。
-
Tuple 没有的方法:
1、不能向 tuple 增加元素,没有 append 、 extend 、insert 等方法。
2、 不能从 tuple 删除元素,没有 remove 或 pop 方法。
3、 不能在 tuple 中查找元素,没有 index 方法(index是查找而不是索引,索引直接用下标即可,如:t[0])。
Lsit的操作
含义 | 运算 | 结果 |
---|---|---|
替换 | s[i] =x | s中第i项替换为x |
切片替换 | s[i:j]=s1 | 将s从i到j的切片替换为可迭代对象s1的内容 |
删除 | del s[i:j] | 删除s[i:j] |
添加 | s.append(x) | 将x 添加到序列的末尾 |
清空 | s.clear() | 移除s中所有元素(等同于del s[:]) |
复制 | s.copy() | 创建s的浅拷贝(等同于s[:]) |
扩展 | s.extend(t) | 等于s+=t |
插入 | s.insert(i,x) | 给定索引i处插入元素x |
提取并移除 | s.pop(i) | 提取并移除给定索引位置的元素 |
移除 | s.remove(x) | 移除元素x |
翻转 | s.reverse() | s逆序排列 |
- del 与clear区别
del s:将s删除;
s.clear():只是将s里的元素清空.
字典
- 新增元素
#输入:
x = {'Christopher Brooks': 'brooksch@umich.edu', 'Bill Gates': 'billg@microsoft.com'}
x['Christopher Brooks'] # Retrieve a value by using the indexing operator
#输出:
'brooksch@umich.edu'
- 遍历
#遍历Key
for key in x:
print(x[key])
#遍历value
for value in x.values():
print(value )
#遍历所有项
for key , value in x.items():
print(key ,value )
- 拆分序列
#确保一一对应即数量的匹配
x = ('Christopher', 'Brooks', 'brooksch@umich.edu')
fname, lname, email = x
- 其他方法
D.get(key, 0) #同dict[key],多了个没有则返回缺省值,0。[]没有则抛异常
D.has_key(key) #有该键返回TRUE,否则FALSE
D.keys() #返回字典键的列表
D.values()
D.items()
D.update(dict2) #增加合并字典
D.popitem() #得到一个pair,并从字典中删除它。已空则抛异常
D.clear() #清空字典,同del dict
D.copy() #拷贝字典
D.cmp(dict1,dict2) #比较字典,(优先级为元素个数、键大小、键值大小)
#第一个大返回1,小返回-1,一样返回0
#dictionary的复制
dict1 = dict #别名
dict2=dict.copy() #克隆,即另一个拷贝。