Python基础知识

无论是数据分析,还是机器学习,Python总是绕不开的重要语言,这里是自己整理的一些Python基础知识。推荐大家使用Python3。

1. 基本数据类型

Number 数字
String 字符串
List 列表
Tuple 元组
Set 集合
Dictionary 字典

其中

不可变数据:数字,字符串,元组
可变数据:列表,字典,集合

2. 数字 Number

类型:int,float,bool,complex
数学函数:abs(x)绝对值
ceil(x)向上取整数
floor(x)向下取整
max(x1,x2,…)最大
min(x1,x2,…)最小
pow(x,y)x的y次方
round(x,[n])精确到x的n位
随机数:random.choice(range(10))
随机返回一个0~10的整数
random.uniform(1,3)
随机生成一个1到3的实数

3. 字符串 String

3.1 访问

var = 'hello word'
var[0]--h
var[1:4]--ell

3.2 转义字符

\000  空
\n    换行
\v    纵向制表符
\t    横向制表符
\r    回车
\f    换页

3.3 拼接

+ 字符串拼接
* 重复输出,如a='x',a*2--xx

3.4 格式化

%s 格式化字符串
%d 格式化整数
%f 格式化浮点数

3.5 函数

count() 范围内字符出现次数
len() 返回长度
lower() 转为小写
upper() 转为大写
title() 标题化字符串,首字母大写    r
min(str) 取最小字符串
man(str) 取最大字符串
find() 检查字符串是否在字符中
repleace(new,old,[max]) 替换old为new,如果max存在则不超过max次
strip() 删除空格

4. 列表

使用方括号括起,用逗号隔开。

4.1 访问

使用[],[:]

4.2 删除

del list[] 也可指定位置

4.3 函数

len(list) 元素个数
max(list) 最大值元素
min(list) 最小值元素
list(seq) 元组转换为列表

4.4 方法

list.append(obj) 末尾添加新元素
list.count(obj) 同级元素出现次数
list.extend(seq) 新列表扩展旧列表
list.index(obj) 某个值第一个匹配项的索引位置
list.insert(index, obj) 将对象插入列表
list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj) 移除列表中某个值的第一个匹配项
list.reverse() 反向列表中元素
list.sort() 对原列表进行排序
list.sort(reverse=True) 反向排序

5. 元组

元组与列表类似,但元组不能修改,元组使用小括号。访问,删除同列表。
tuple(seq) 将列表转化为元组

6. 字典

每个键值对用:分割,放在花括号{}中,在Pandas中会经常用到字典。

1
2
dict = {key1:value1,key2:value2}
键唯一,值不必。

6.1 访问

1
2
dict={'name':'jack','age':7,'class':1}
dict['name']--jack

6.2 修改

1
dict['age']=8

6.3 删除

1
2
3
del dict['name']
del dict
del.clear()

6.4 函数

cmp(dict1, dict2) 比较两个字典元素
len(dict) 键的总数
str(dict) 输出字符串表示
type(variable) 返回输入的变量类型

6.5 方法

dict.clear() 删除所有元素
dict.copy() 返回浅复制
dict.get(key, default=None) 返回指定键的值
dict.has_key(key) 键是否在字典
dict.items() 以列表返回可遍历的(键, 值) 元组数组
dict.keys() 以列表返回所有的键
dict.values() 以列表返回所有的值
dict.update(dict2) 把字典dict2的键/值对更新到dict里
pop(key[,default]) 删除字典给定键 key 
popitem() 随机返回并删除字典中的一对键和值

7. 条件控制和循环

7.1 一般形式

1
2
3
4
if 条件:
语句
else
语句

7.2 while循环

1
2
3
4
5
6
while 条件:
语句
while 条件:
语句
else:
语句

7.3 for循环

1
2
3
4
for 变量 in 序列:
语句
else:
语句

7.4 遍历

1
2
for i in range(5): 同理#range(5,9),range(0,10,3)
print(i)
输出 0到4
列表遍历:
1
2
for a in list:
print(a)
字典遍历:
1
2
for k,v in dict:
print(k,v)#也可分别遍历

7.5 break 和 continue

break跳出循环,之后语句不再执行。
continue跳过当前循环,继续指向下一循环。

7.6 pass语句

pass 不做任何事情,一般用做占位语句。

8. 函数

def 函数名(参数列表):
函数体

8.1参数

必备参数

必备参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。

1
2
3
4
5
def printme( str ):
print( str );
return;
调用:
printme( str );

关键字参数

传参顺序不需指定。

1
2
3
4
5
6
7
8
9
def printinfo( name, age ):
print("Name: ", name);
print("Age ", age);
return;
调用:
printinfo( age=50, name="miki" );
输出:
Name: miki
Age 50

缺省参数

调用函数时,缺省参数的值如果没有传入,则被认为是默认值。

1
2
def printinfo( name, age = 35 ):
printinfo( name="miki" )#则默认输出age=15;

不定长参数

你可能需要一个函数能处理比当初声明时更多的参数。

1
2
3
4
5
6
7
8
9
def printinfo( arg1, *vartuple ):
print("输出: ")
print(arg1)
for var in vartuple:
print (var)
return;
调用:
printinfo( 10 );
printinfo( 70, 60, 50 );

8.2 变量作用域

L(Local)
E(Enclosing)
G(Global)
B(Built-in)
以L→E→G→B规则查找。

9. 输入和输出

9.1 键盘读入

1
2
str = input("请输入:");
print ("内容是: ", str)

9.2 文件读写

读文件
1
2
3
4
f = open("/tmp/foo.txt", "r")
str = f.read()
print(str)
f.close()
写文件(覆盖)
1
2
3
f = open("/tmp/foo.txt", "w")
f.write( "Python 非常好。\n是的!\n" )
f.close()
写文件(追加)
1
2
3
f = open("/tmp/foo.txt", "a")
f.write( "Python 非常好。\n是的!\n" )
f.close()

10. 错误和异常

异常处理

1
2
3
4
5
6
7
8
while True:
try:
x = int(input("输入数字"))
break
except ValueError:
print("不是数字")
else:
print("数字是:",x)

带参异常

1
2
3
4
5
6
def temp_convert(var):
try:
return int(var)
except (ValueError) as Argument:
print ("参数没有包含数字\n", Argument)
temp_convert("xyz");

抛出异常

raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类(也就是 Exception 的子类)。如果你只想知道这是否抛出了一个异常,并不想去处理它,那么一个简单的 raise 语句就可以再次把它抛出。

1
2
3
4
5
6
7
8
9
10
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise

An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: HiThere

自定义异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)

try:
raise MyError(2*2)
except MyError as e:
print('My exception occurred, value:', e.value)

My exception occurred, value: 4
raise MyError('oops!')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'