My_Python的常用函数.

范围生成函数

 

1 class range(object)
2  |  range(stop) -> range object
3  |  range(start, stop[, step]) -> range object
4  |  
5  |  Return an object that produces a sequence of integers from start (inclusive)
6  |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
7  |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
8  |  These are exactly the valid indices for a list of 4 elements.
9  |  When step is given, it specifies the increment (or decrement).

 

大致意思就是前闭后开.产生一个有序序列 .

 

 1 >>> for i in range(10,21):
 2     print(i,"\n")
 3 
 4     
 5 10 
 6 
 7 11 
 8 
 9 12 
10 
11 13 
12 
13 14 
14 
15 15 
16 
17 16 
18 
19 17 
20 
21 18 
22 
23 19 
24 
25 20 

随机数生成函数

 

1 randint(a, b) method of random.Random instance
2     Return random integer in range [a, b], including both end points.// 包括两端的端点.

 

 

 

 1 >>> import random
 2 >>> for i in range(10):
 3     print(random.randint(1,100))
 4 
 5     
 6 31
 7 60
 8 29
 9 46
10 10
11 25
12 72
13 16
14 14
15 72

匿名函数(Lambda)

1 >>> g=lambda x : x*2+1
2 >>> g(5)
3 11

不用费尽心思的想名字(有意义,不重复) . 随便给个名字等不用的时候  内存就把它回收了.

 1 >>> g=lambda x : x*2+1
 2 >>> g(5)
 3 11
 4 >>> def add(x,y):
 5     return x+y
 6 
 7 >>> add(3,4)
 8 7
 9 >>> f=lambda x,y:x+y
10 >>> f(3,4)
11 7

过滤器(Filter)

可以将文件中不合本意的东西给过滤掉.

1 class filter(object)
2  |  filter(function or None, iterable) --> filter object
3  |  
4  |  Return an iterator yielding those items of iterable for which function(item)
5  |  is true. If function is None, return the items that are true.

大概意思就是说,这个函数其中可以放两个参数,第一个参数是 Funtion或者是None 第二个是一个可迭代列表. 用函数来确定列表中的真假 , 将其中为真的再生成一个新的列表, 如果为none 则直接看列表中数据的真假,将其中为真的再去形成一个列表就行.         下面举个例子,

 1 >>> def odd(x):
 2     return x%2
 3 
 4 >>> # 声明了 Function .
 5 >>> result=filter(odd(),range(10))
 6 Traceback (most recent call last):
 7   File "<pyshell#4>", line 1, in <module>
 8     result=filter(odd(),range(10))
 9 TypeError: odd() missing 1 required positional argument: 'x'
10 >>> result=filter(odd,range(10))
11 >>> result
12 <filter object at 0x02F809D0>
13 >>> list(result)
14 [1, 3, 5, 7, 9]

在  "result=filter(odd(),range(10))"  中得到的是一个  "<filter object at 0x02F809D0>"  需要将其转换为   list.            现学现用,lambda的使用

 

1 >>> list(filter(lambda x:x%2,range(10)))
2 [1, 3, 5, 7, 9]

 

map(映射)

1 class map(object) 2 | map(func, *iterables) --> map object 3 | 4 | Make an iterator that computes the function using arguments from 5 | each of the iterables. Stops when the shortest iterable is exhausted. 6 |

也是有两个参数第一个是Function 第二个是可迭代数据. 将可迭代数据中的一个个数据作为自变量传入 Function 然后得到映射 . 

这里是新鲜的例子.  

1 >>> list(map(lambda x:x*2,range(10)))
2 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

 

 

 

posted @ 2016-07-11 16:25  X-POWER  阅读(1612)  评论(0编辑  收藏  举报