Python notes

1. range()函数的使用:

a = range(n)   # a = range(0,n)
b = range(m,n) # b = range(m,n)

alist = list(a) # alist = [0, 1, ... , n-1]
blist = list(b) # blist = [m, m+1, ... , n-1] #notice: 均不包含n,即类似左闭右开的区间形式 [... ...)

 

2. import ... 与  from ... import * 的区别:

#使用numpy包含的模块时需要在前面加np
import
numpy as np a = np.array([1, 2, 3, 4])
#直接调用numpy包含的模块
from
numpy import * a = array([1, 2, 3, 4])

 

3. list列表操作

#获取长度
listLen = len(sampleList)
#遍历list中元素
for element in list:
    print(element)
#删除元素
del sampleList[2:4]
#浅拷贝与深拷贝
lista = [1, 4, 2, 5, 3]
listb = lista
listc = lista[:]

lista.sort()  # lsita = [1, 2, 3, 4, 5]
print(listb)  # listb = [1, 2, 3, 4, 5]
print(listc)  # listc = [1, 4, 2, 5, 3]
sample_list.append(var)   #追加元素
sample_list.insert(index,var)
sample_list.pop(var)      #返回最后一个元素,并从list中删除之
sample_list.remove(var)   #删除第一次出现的该元素
sample_list.count(var)    #该元素在列表中出现的个数
sample_list.index(var)    #该元素的位置,无则抛异常 
sample_list.extend(list)  #追加list,即合并list到L上
sample_list.sort()        #排序
sample_list.reverse()     #倒序

 

4. 判断数据类型 if type(sample)==type(1):         #判断sample是否为int

 

5. 格式化输出 print("The sample number is %d and %f" %(4,2))  #The sample number is 4 and 2.000000

 

6. 条件选择  if: ... elif: ...

 

7. 绘制散点图 (matplotlib官网给出了大量绘图样例,非常棒,想要绘制图形可以参考)

matlbplot的plot函数,很好用,与matlab中的plot类似

 

8. python的在传递list时使用的是引用(reference),因此如果list的值在一个函数中被改变,则它在所有地方都会是改变后的值。

 

9. 集合类型(set):一无序不重复元素集。基本功能包括关系测试和消除重复元素

a = [1, 2, 3, 3, 4, 5, 5]
b = set(a)  #b = set([1, 2, 3, 4, 5]) 
setA = set([1 ,2 , 3, 4])
setB = set([3 ,4 , 5, 6])
setC = setA | setB   # 并集 setC = set([1, 2, 3, 4, 5, 6])
setC = setA & setB   # 交集 setC = set([3, 4])
setC = setA - setB   # 差集 setC = set([1, 2])
setC = setA ^ setB   # 对称差集 setC = set(1, 2, 5, 6)

 

10. 排序函数sorted与sort

from operator import itemgetter, attrgetter  

list_a = [1, 5, 4, 2, 3]
list_a.sort()                            # list_a = [1, 2, 3, 4, 5]
list_b = sorted(list_a, reverse = True)  # list_b = [5, 4, 3, 2, 1]

list_a = [("li si", "D", 12), ("xiao ming", "A", 15), ("ma zi", "A",  14), ("wang er", "B", 10)]  
list_b = sorted(dic_a, key = itemgetter(1, 2), reverse = True)  
# sort by grade then by age 
# list_b = [("li si", "D", 12), ("wang er", "B", 10), ("xiao ming", "A", 15), ("ma zi", "A", 14)]

 

posted @ 2015-05-07 09:54  universe  阅读(279)  评论(0编辑  收藏  举报