一些基础函数的笔记

1.round() 按指定的位数对数值进行四舍五入

>> round(3.1415926,2)  #小数点后两位
3.14  
>>> round(3.1415926)#默认为0  
3  
>>> round(3.1415926,-2)  
0.0  
>>> round(3.1415926,-1)  
0.0  
>>> round(314.15926,-1)  
310.0  
>>>print "round(80.23456, 2) : ", round(80.23456, 2)
round(80.23456, 2) :  80.23
>>>print "round(100.000056, 3) : ", round(100.000056, 3)
round(100.000056, 3) :  100.0
>>>print "round(-100.000056, 3) : ", round(-100.000056, 3)
round(-100.000056, 3) :  -100.0
>>> [str(round(355/113, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

2.set()是一个无序不重复元素集,不记录元素位置或者插入点, 基本功能包括关系测试和消除重复元素. 集合内元素支持交并差等数学运算.

>>> x = set('spam')
>>> y = set(['h','a','m'])
>>> x, y
(set(['a', 'p', 's', 'm']), set(['a', 'h', 'm']))
>>> x & y # 交集
set(['a', 'm'])
>>> x | y # 并集
set(['a', 'p', 's', 'h', 'm'])
>>> x - y # 差集
set(['p', 's'])


去除海量列表里重复元素,用hash来解决也行,不过在性能上不是很高,用set解决只需几行代码

>>> a = [11,22,33,44,11,22]
>>> b = set(a)
>>> b
set([33, 11, 44, 22])
>>> c = [i for i in b]
>>> c
[33, 11, 44, 22]


3.嵌套列表

>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]


4. strip() 方法用于移除字符串头尾指定的字符(默认为空格)。

>>>str = "0000000this is string example....wow!!!0000000";
>>>print str.strip( '0' );
this is string example....wow!!!'
>>> a = ' 123'
>>> a.strip()
'123'
>>> a='\t\tabc'
'abc'
>>> a = 'sdff\r\n'
>>> a.strip()
'sdff'




5.rjust() , 它可以将字符串靠右, 并在左边填充空格

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # Note use of 'end' on previous line 注意前一行 'end' 的使用
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729




另一个方法 zfill(), 它会在数字的左边填充 0,
>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'




6.str.format() 
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"


括号及其里面的字符 (称作格式化字段) 将会被 format() 中的参数替换。


在括号中的数字用于指向传入对象在 format() 中的位置,如下所示:
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam




如果在 format() 中使用了关键字参数, 那么它们的值会指向使用该名字的参数。
>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.


>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...     print('{0:10} ==> {1:10d}'.format(name, phone))
...
Jack       ==>       4098
Dcab       ==>       7678
Sjoerd     ==>       4127



7.range() ,生成数列
>>>range(1,5)#代表从1到5(不包含5)
[1,2,3,4]
>>>range(1,5,2)#代表从1到5,间隔2(不包含5)
[1,3]
>>>range(5)#代表从0到5(不包含5)
[0,1,2,3,4]


posted @ 2017-03-12 23:36  fanren224  阅读(237)  评论(0编辑  收藏  举报