operator.itemgetter函数
operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子。
a = [1,2,3]
>>> b=operator.itemgetter(1) //定义函数b,获取对象的第1个域的值
>>> b(a)
2
>>> b=operator.itemgetter(1,0) //定义函数b,获取对象的第1个域和第0个的值
>>> b(a)
(2, 1)
在使用ipython的过程当中,如果一个程序没有报错error,但是我们依然需要去查看程序当中的变量的时候我们应该怎么办呢,,,?因为没有error意味着就没办法debug了,一个使用的小技巧如下图所示:
比如我们想要查看变量sortedClassCount,我们可以在下面插入1/0,那么程序就会报错提示ZeroDivisionError: integer division or modulo by zero,这个时候我们就可以进入debug模式进行变量查询检查了!
关于字典排序:(字典到列表形式的变化)
dic={5:2,3:7,0:1,9:4}
import operator
sorted(dic.iteritems(),key=operator.itemgetter(1),reverse=True)
Out[9]: [(3, 7), (9, 4), (5, 2), (0, 1)]
l=sorted(dic.iteritems(),key=operator.itemgetter(1),reverse=True)
l
Out[11]: [(3, 7), (9, 4), (5, 2), (0, 1)]
type(l)
Out[12]: list
import numpy
numpy.zeros((1,4))
Out[2]: array([[ 0., 0., 0., 0.]])
numpy.zeros(1,4)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-b69104f6a86c> in <module>()
----> 1 numpy.zeros(1,4)
TypeError: data type not understood
raw_input和sys.stdin.readline()的不同之处:两个都可以通过屏幕获取输入,但是有细微的差别;
import sys
line=sys.stdin.readline()
for i in range(len(line)):
print line[i]+'hello'
发现输出结果总是多出来了一个hello,这是因为通过sys.stdin.readline()的方式获取的时候把输入结尾的 '\n' 一同读入,所以len的时候总是多一个的,我们修改程序如下(去掉回车符):
import sys
line=sys.stdin.readline().strip('\n')
for i in range(len(line)):
print line[i]+'hello'
而通过raw_input()则没有这样的问题:
c=raw_input()
aaa123
c
Out[20]: 'aaa123 '
c=raw_input()
aaa123 bb12
c
Out[22]: 'aaa123 bb12'
python去掉小数位:
a=numpy.floor(1.2345)
a
Out[8]: 1.0
type(a)
Out[9]: numpy.float64
a=int(a)
a
Out[11]: 1
type(a)
Out[12]: int
insert的用法,以下实例展示了 insert()函数的使用方法:
#!/usr/bin/python aList = [123, 'xyz', 'zara', 'abc'] aList.insert( 3, 2009) print "Final List : ", aList
以上实例输出结果如下:
Final List : [123, 'xyz', 'zara', 2009, 'abc'] #在元素的前面插入
Sorted 排序
import numpy
import operator
te={"a":1,"b":5,"c":9}
t=sorted(te.iteritems(),key=operator.itemgetter(1),reverse=True)
t
Out[18]: [('c', 9), ('b', 5), ('a', 1)]
t[0][1]
Out[19]: 9
nonzero()的用法含义:
如果 a=mat([ [1,0,0],
[0,0,0],
[0,0,0]])
则 nonzero(a) 返回值为(array([0]), array([0])) , 因为矩阵a只有一个非零值, 在第0行, 第0列。
如果 a=mat([ [1,0,0],
[1,0,0],
[0,0,0]])
则 nonzero(a) 返回值为(array([0, 1]), array([0, 0])) , 因为矩阵a只有两个非零值, 在第0行、第0列,和第1行、第0列。所以结果元组中,第一个行维度数据为(0,1) 元组第二个列维度都为(0,0)。
import re
shouru='money<=97'
re.compile("(<=.+)").search(shouru).group() #group出来
Out[4]: '<=97'
re.compile("(<=.+)").search(shouru).group()[2:]
Out[5]: '97'
re.compile("(<=.+)").search(shouru)
Out[6]: <_sre.SRE_Match at 0x39c6378> #返回一个对象
#(<=.+) .表示省略的意思 等号后面还有内容 +表示重复至少一次
re.compile("<=.+").search(shouru).group()[2:]
Out[8]: '97'
re.compile("<=.+").search(shouru).group()[:-2]
Out[9]: '<='
re.compile(".+<=").search(shouru).group()[:-2] # 'money<='
Out[11]: 'money'