Python入门实践案例
1、基本语法
#我是注释
print('hello world') #打印出:hello world
print("hello world") #打印出:hello world
x=3 #变量赋值,不需要声明变量类型
print(type(x)) #打印出:<type 'int'>
print(x+1) #打印出:4
print(x*2,x**2,x/2) #可以打印多个,打印出:6 9 1 1.5
x +=1
print(x) #打印出:4
结果如下所示。
2、 数据类型
2.1、数字
整数和浮点数与其他语言类似,Python支持很多数字的操作:加减乘除幂。例外:不支持x++和++x类型的操作。
x = 3
print(type(x)) # 打印 "<type 'int'>"
print(x + 1,x - 1, x * 2,x/2, x ** 2) #加减乘除幂
x += 1
print(x) # Print "4"
x *= 2
print(x) # Print "8"
y = 2.5
print(type(y)) # Print "<type 'float'>"
print(y, y + 1, y * 2, y ** 2) # Print "2.5 3.5 5.0 6.25"
结果如下所示。
2.2、布尔
Python的布尔类型支持常见的与、或、非、异或 注意:与或非布尔操作不是使用操作符而是使用关键词 and/or/not。
t = True
f = False
print(type(t)) #
print(t and f) # 与 AND;
print(t or f) # 或 OR;
print(not t) # 非 NOT;
print(t != f) # 异或 XOR;
结果如下所示。
2.3 字符串
S = 'Princetechs'
print(len(S)) #求长度
print(S[0],S[1],S[-1],S[-2],S[len(S)-1]) #索引
print(S,S[1:3],S[1:],S[:3],S[:-1],S[:])#切片
print(S+'xyz',S*3) #合并和重复
结果如下所示。
S='Z'+S[1:]
print(S)
结果如下所示。
Zrincetechs
1、字符串特定函数
S.find('Prince')
print(S.replace('Prince','XYZ'))
print(S.upper())
line='aa,bb,ccc,dd'
print(line.split(','))
line='aa,bb,ccc,dd\n'
print(line.rstrip())
print(' world '.strip())
hw12='%s %s %d' % ('hello','world',12) #格式化字符串
print(hw12)
结果如下所示。
line='aa,bb,ccc,dd'
print(line.split(','))
结果如下所示。
[‘aa’, ‘bb’, ‘ccc’, ‘dd’]
hw12='%s %s %d' % ('hello','test',12) #格式化字符串
print(hw12)
结果如下所示。
hello test 12
3、列表
animals = ['cat', 'dog', 'monkey']
#列表元素遍历
for animal in animals:
print(animal)
#遍历并获取元素索引
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))
#列表推导式
squares = [x*2 for x in animals]
print(squares)
结果如下所示。
list1 = [12,45,32,55]
list1[0] = "good"
print(list1)
结果如下所示。
[‘good’, 45, 32, 55]
list2 = [x*3 for x in list1]
print(list2)
结果如下所示。
[‘goodgoodgood’, 135, 96, 165]
4、元组
T=(1,2,3) #创建元组
T+(4,5) #元组合并,输出:(1, 2, 3, 4, 5)
t=(42,) #只有一个元素的元组,区别于数字
list1 = (12,45,32,55)
#list1[0] = "good"
print(list1[0])
结果如下所示。
12
5、集合
sample_set = {'Prince', 'Techs'}
print('Data' in sample_set) # 检查集合中是否存在某一元素
sample_set.add('Data') # 增加元素
print('Data' in sample_set)
print(len(sample_set) ) # 打印集合大小
sample_set.remove('Data') # 删除元素
print(len(animals))
结果如下所示。
False
True
3
3
sample_set = {'Prince','Techs','Prince'}
print(sample_set)
结果如下所示。
{‘Prince’, ‘Techs’}
1、集合元素遍历
for idx, word in enumerate(sample_set):
print('#%d: %s' % (idx + 1, word))
#集合推导式
from math import sqrt
nums = {int(sqrt(x)) for x in range(100)}
print(nums) # Prints "set([0, 1, 2, 3, 4, 5])"
结果如下所示。
#1: Prince
#2: Techs
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
from math import sqrt
nums = {int(sqrt(x)) for x in range(100)}
print(len(nums))
print(nums)
结果如下所示。
10
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
6、字典
字典的创建方式
D1 = {'food':'Spam','quantity':4,'color':'pink'}
D2 = dict(food='Spam',quantity=4, color='pink')
D3 = dict([("food", "1"),("b", "2")])
1、复制
x=dict(food='Spam',quantity=4, color='pink')
y=x.copy()
y['color'] = 'red'
print(x)
print(y)
结果如下所示。
{‘color’: ‘pink’, ‘food’: ‘Spam’, ‘quantity’: 4}
{‘color’: ‘red’, ‘food’: ‘Spam’, ‘quantity’: 4}
2、元素访问
d={}
#print(d['name'] #得到错误信息
print(d.get('name')) #打印出:None
print(d.get('name',u'键值不存在!'))
结果如下所示。
None
键值不存在!
d={}
#print(d['name'] #得到错误信息
print(d.get('name')) #打印出:None
print(d.get('name',u'键值不存在!'))
d=dict(title='hackdata',url='www.hackdata.cn',spam=0)
print(d.keys())
print(d.values())
print(d.items())
结果如下所示。
False
[‘url’, ‘spam’, ‘title’]
[‘www.hackdata.cn’, 0, ‘hackdata’]
[(‘url’, ‘www.hackdata.cn’), (‘spam’, 0), (‘title’, ‘hackdata’)]
7、控制流
7.1、if 条件语句
review_sentiment = -1
if review_sentiment > 0:
print('positive')
elif review_sentiment == 0:
print('neutral')
else:
print('negative')
结果如下所示。
negative
7.2、假值情况
tests = [False,None,0,(),{},[],""]
for test in tests:
if test:
print(True)
else:
print(False)
结果如下所示。
t = True
f = False
print(type(t)) #打印出:<type ‘bool’>
print(t and f)#打印出:False
print(t or f) #打印出:True
print(not t) #打印出:False
结果如下所示。
<type ‘bool’>
False
True
False
7.3、while循环
x,y=1,1
while x<=20 and y<=20:
print(x)
if x>9:
break
y+=1;x=x+y
结果如下所示。
1
3
6
10
7.4、for循环
L = [5,-2,4,0,1,3]
for x in range(len(L)):
L[x]+=1
print(L)
d = {'person':2,'spider':8}
for animal in d:
legs = d[animal]
print('A %s has %d legs' % (animal,legs))
结果如下所示。
A person has 2 legs
A spider has 8 legs
8、函数
def fibs(num,b=3):
result=[0,1]
for i in range(num-2):
result.append(result[-2]+result[-1])
return result
print(fibs(7)) #输出:[0, 1, 1, 2, 3, 5, 8]
结果如下所示。
[0, 1, 1, 2, 3, 5, 8]
def hello(greeting='hello', name='world'):
print('%s, %s!' % (greeting, name))
hello()
hello('Greetings')
hello('Greetings', 'universe')
hello(name='Gumby')
结果如下所示。
使用input函数来获取用户输入
x=input('Please enter the first number: ')
y=input('Please enter the second number: ')
print(x+y)
结果如下所示。
Please enter the first number: 2
Please enter the second number: 2
22
9、类
class Greeter(object):
# 构造方法
def __init__(self, name):
self.name = name # 创建一个实例变量
# 实例方法
def greet(self, loud=False):
if loud:
print('HELLO, %s!' % self.name.upper())
else:
print('Hello, %s' % self.name)
g = Greeter('Fred') # 创建Greeter类的一个实例
g.greet() # 调用实例方法,使用默认参数
g.greet(loud=True) # 调用实例方法,自定义参数
结果如下所示。
Hello, Fred
HELLO, FRED!
2、科学计算
2.1numpy
import numpy as np
a = np.array([1, 2, 3]) # 创建一位数组
print(type(a)) # 打印类型
print(a.shape) # 打印数组形状
print(a[0], a[1], a[2]) # 打印数组元素
a[0] = 5 # 改变元素取值
print(a) # 打印整个数组
b = np.array([[1,2,3],[4,5,6]]) # 创建二维数组
print(b.shape) # 形状
print(b[0, 0], b[0, 1], b[1, 0]) # 打印数组元素
结果如下所示。
<class ‘numpy.ndarray’>
(3,)
1 2 3
[5 2 3]
(2, 3)
1 2 4
1、numpy的数据类型
arr1 = np.array([1,2,3],dtype=np.float64)
arr2 = np.array([1,2,3],dtype=np.int32)
print(arr1.dtype)
print(arr2.dtype)
结果如下所示。
float64
int32
2、索引和切片
arr = np.arange(10)
arr_slice = arr[5:8]
arr_slice[1] = 999
print(arr)
arr_slice[:]=14
print(arr)
结果如下所示。
[ 0 1 2 3 4 5 999 7 8 9]
[ 0 1 2 3 4 14 14 14 8 9]
names = np.array(['Bob','Will','Bob','Joe'])
data = np.array([[-3,2,0,-1],[1,2,3,-4],
[2.5,1.7,-0.2,1],[-8,-4,9,10]])
print(data[names=='Bob'])
print(data[names=='Bob',2:])
结果如下所示
[[-3. 2. 0. -1. ]
[ 2.5 1.7 -0.2 1. ]]
[[ 0. -1. ]
[-0.2 1. ]]
3、基本统计方法
arr = np.arange(20).reshape((4,5))
print(arr.mean())
print(arr.sum())
print(arr.mean(1))
print(arr.sum(0))
print(arr.cumsum(0))
print(arr.cumprod(1))
samples = np.random.normal(size=(4,4))
print(samples)
结果如下所示。
2.2、matplotlib
1、plot绘图
#绘制曲线图
plt.plot(x, y)
plt.show()
#子图绘制
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.subplot(2, 1, 1)
plt.plot(x, y_sin) # 绘制第一个子图
plt.title('Sine')
plt.subplot(2, 1, 2) # 绘制第二个子图
plt.plot(x, y_cos)
plt.title('Cosine')
plt.show()
结果如下所示。
2.3、Pandas
import pandas as pd
ts = pd.Series([1,2,3,4],index=list('dbac'))
print(ts)
print(ts.values)
print(ts.index)
结果如下所示。
ts.index=list('mnop') #修改索引
print(ts)
结果如下所示。
#通过字典构建Series对象
dict1 = dict(d=4,b=7,a=-5,c=3)
ts2 = pd.Series(dict1)
print(ts2)
结果如下所示。
print(ts2.index.name)
结果如下所示。
None
#获取某一列Series
print(frame['name'])
#获取某一列Series
print(frame.ix[1])
结果如下所示。
print(frame.drop('name',axis=1))
print(frame) #frame 本身并未改变
del frame['name']
print(frame) #name列删除
结果如下所示。
print(frame[frame['age'] > 19])
结果如下所示。
age
0 21
2 20
print(frame)
结果如下所示。
print(frame.describe())
结果如下所示。
frame['num_friends']=[3,5,8]
print(frame.cov())
结果如下所示。
print(frame.corr())
结果如下所示。