Python简介/Introduction to Python2

3Functions and Packages

3.1Familiar functions

len() Length of list or string
int()
max() maximum of list
print()

3.2help

complex number 复数
real part 实部
imaginary part 虚部
square brackets 方括号
help(max) help(complex)

3.3 Multiple argument

in descending/ascending order 降序/升序排序

#sorted(iterable, key=None, reverse = False)
#False表示升序/True表降序
a=[1, 2, 31, 3, 4, 11, 2.4, 5.6]
b=sorted(a,reverse = True) #b=[31, 11, 5.6, 4, 3, 2.4, 2, 1]
#key指定自定义排列顺序??

3.4 Method

  • Functions that belong to objects
  • methods : call function on objects
  • Everything = object
  • Object have methods associated, depending on type(不同类型的对象对应不同的方法)
type examples of methods
object str captitalize(), replace()
object int bit_length(), conjugate()
object list index(), count()
fam = ['liz', 1.3, 'emma', 1.68]

fam.index("emma") # 2
sister = 'liz'
a=sister.capitalize() # a='Liz'
b=sister.replace('z', 'sa') # b='lisa'

3.4.1 string method

#string to experiment with: place
place = "poolhouse"
#Use upper()on place: place_up
place_up = place.upper() # 全部大写
#Print out place and place_up
print(place,place_up)# poolhouse POOLHOUSE
#Print out the number of o’s in place
print(place.count('o'))# 3

3.4.2 list methods

#create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
#Print out the index of the element 20.0
print(areas.index(20.0)) #2
#Print out how often 9.50 appears in areas
print(areas.count(9.50))#1
#Reverse the orders of the elements in areas
areas.reverse() #翻转
print(areas) # [9.5, 10.75, 20.0, 18.0, 11.25]

3.5 Packages

numpy - arrays数组
matplotlib - data visualization
scikitlearn - machine learning

3.5.1 install package

http://pip.readthedocs.org/en/stable/installing/
Download get-pip.py
Terminal:
python3 get-pip.py
pip3 install numpy #安装包numpy

3.5.2 import package

AAA
import numpy #import the entire numpy package
numpy.array([1, 2, 3])
BBB(selective import)
import numpy as np
np.array([1, 2, 3])
CCC
from numpy import array
array([1, 2, 3])

AAAe.g:
r = 0.43
import math
C = 2*math.pi*r #计算周长
A = math.pi*r**2 #计算面积

#Suppose you want to use the function inv(), which is in the linalg subpackage of the scipy package.
from scipy.linalg import inv as my_inv

没有更多推荐了,返回首页