Python-一些实用的函数

一,返回值为bool类型的函数

1.any()函数

  any(iterable)->bool

  当迭代器中有一个是Ture,则返回Ture;若interable=NUll,则返回False.

>>> any([1,0])
True
>>> any([0,0])
False
>>> any([])
False
>>> any([1,0,0])
True

注:在Python中, False相当于:0,[], (), {}, 0.0 , " ", ' ' .

应用:在一颗二叉树中,找出每一层中的最大元素(leetcode515)。

Input: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

Output: [1, 3,9] 

#类节点的定义
class
node(self) : def __init__(self,data) self.val=data self.right=NULL self.left=NULL

class Solution(object): def largestValues(self, root): maxlist=[] row=[root] while any(row): maxlist.append(max[node.val for node in row]) row=[kid for node in row for kid in node.left,node.right) if kid] return maxlist

2.all()函数

 all(iterable)->bool

 迭代器中每个元素必须都为真时,返回Ture,否则返回False.

>>> all([1,0])
False
>>> all(["e",1])
True

3.isinstance(),issubclass()

1.isinstance(object, classinfo) ->bool.返回True如果参数object是classinfo的一个实例,否则返回False。

2.issubclass(class, classinfo) .返回True如果参数class是classinfo的一个子类,否则返回False。

待续中。。。

二,内置高阶函数(可以接受函数名为参数的函数)

    高阶函数:在数学中类似于算子,高阶导数,复合函数,也就是说把函数当作自变量,通过某种对应关系映射得到一个新的函数。在Python中常见内置的高阶函数有:mape(),reduce(),filter(),sortded()

1.map()

     map(function_name,list)->list 。map()将接受 一个函数与列表为参数,返回一个新的列表。这个函数依次对列表中的每个元素进行操作,返回得到的结果,组成一个列表作为输出的结果。

列如:

def string_len(str):

    return {str[0].upper()+str[1:].lower():len(str)}

strlist=['whb','hello,world','day day up']
print map(string_len,strlist)

>>> [{'Whb': 3}, {'Hello,world': 11}, {'Day day up': 10}]

实现,map()函数的作用相当于迭代,我们只需要定义一个实现我们想要的子结果的函数即可。

2.reduce()

reduce把一个函数f(x,y)作用在一个序列[x1, x2, x3…]上,f(x,y)必须接收两个参数x,y,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

>>> def add(x, y):
...     return x + y
... 
>>> reduce(add, [1, 3, 5, 7, 9])
25

3.filter()

filter(f,list)->list;这个f的作用是对list的每个元素进行判断,返回True或False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。

def odd(x):
    return x%2!=0
filter(odd,[1,2,3,4,6,3,6,10,3])

filter(f,list)相当于一个筛子,其中f函数就好像就是一个衡量标准,若list中的元素符合标准,就保留下来。否则就删除掉。

4.sorted()

排序接口:对给定的List L进行排序,
方法1.用List的成员函数sort进行排序,在本地进行排序,不返回副本。
方法2.用built-in函数sorted进行排序(从2.4开始),返回副本,原始输入不变。

>>> a=[1, 54, 6, 90, 8, 9]
>>> b=[33,7,3,1]
>>> a.sort()
>>> a
[1, 6, 8, 9, 54, 90]
>>> sorted(b)
[1, 3, 7, 33]
>>> b
[33, 7, 3, 1]

 sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

其中

(1)  cmp参数
cmp接受一个函数,拿整形举例,形式为:
def f(a,b):
     return a-b
如果排序的元素是其他类型的,如果a逻辑小于b,函数返回负数;a逻辑等于b,函数返回0;a逻辑大于b,函数返回正数就行了
(2)  key参数
key参数的值为一个函数,此函数只有一个参数且返回一个值用来进行比较。这个技术是快速的因为key指定的函数将准确地对每个元素调用。,形式如下
def f(a):
     return len(a)
key接受的函数返回值,表示此元素的权值,sort将按照权值大小进行排序
(3) reverse参数
接受False 或者True 表示是否逆序
 
例如通过key指定的函数来忽略字符串的大小写:
<<< sorted("This is a test string from Andrew".split(), key=str.lower)
   ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
>>> student_tuples = [
        ('john', 'A', 15),
        ('jane', 'B', 12),
        ('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

同样的技术对拥有命名属性的复杂对象也适用,例如:

>>> class Student:
        def __init__(self, name, grade, age):
                self.name = name
                self.grade = grade
                self.age = age
        def __repr__(self):
                return repr((self.name, self.grade, self.age))
>>> student_objects = [
        Student('john', 'A', 15),
        Student('jane', 'B', 12),
        Student('dave', 'B', 10)]
>>> sorted(student_objects, key=lambda student: student.age)   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
sorted里面的key参数的使用非常广泛,因此python提供了一些方便的函数来使得访问方法更加容易和快速。operator模块有itemgetter,attrgetter,从2.6开始还增加了methodcaller方法。使用这些方法,上面的操作将变得更加简洁和快速:

>>> from operator import itemgetter, attrgetter
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
operator模块还允许多级的排序,例如,先以grade,然后再以age来排序
>>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

list.sort()sorted()都接受一个参数reverse(True or False)来表示升序或降序排序。

例如对上面的student降序排序如下:

>>> sorted(student_tuples, key=itemgetter(2), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(student_objects, key=attrgetter('age'), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

待续中。。。

三、类型转换函数

int("5")                        # 转换为整数 integer

float(2)                         # 转换为浮点数 float

long("23")                      # 转换为长整数 long integer

str(2.3)                        # 转换为字符串 string

complex(3, 9)                   # 返回复数 3 + 9i

ord("A")                        # "A"字符对应的数值

chr(65)                          # 数值65对应的字符

unichr(65)                       # 数值65对应的unicode字符

bool(0)                          # 转换为相应的真假值,在Python中,0相当于False

bin(56)                         # 返回一个字符串,表示56的二进制数

hex(56)                         # 返回一个字符串,表示56的十六进制数

oct(56)                         # 返回一个字符串,表示56的八进制数

list((1,2,3))                   # 转换为表 list

tuple([2,3,4])                  # 转换为定值表 tuple

slice(5,2,-1)                    # 构建下标对象 slice

dict(a=1,b="hello",c=[1,2,3])   # 构建词典 dictionary

待续中。。。。

四、字符串处理函数

1、字符串大小写:

str.capitalize

>>> 'hello'.capitalize()

'Hello'

全部大写:str.upper()
全部小写:str.lower()
大小写互换:str.swapcase()

2、字符串替换

str.replace

>>>'hello'.replace('l','2',1)

'he2lo'

可以传三个参数,第三个参数为替换次数

3、字符串切割:

str.split

>>> 'hello'.split('l')
['he', '', 'o']

可以传二个参数,第二个参数为切割次数

4.字符串格式化

获取固定长度,右对齐,左边不够用空格补齐:str.ljust(width)
获取固定长度,左对齐,右边不够用空格补齐:str.rjust(width)
获取固定长度,中间对齐,两边不够用空格补齐:str.centerjust(width)
获取固定长度,右对齐,左边不足用0补齐:str.zfill(width)

>>> str.rjust(40)
'                  python string function'
>>> str.rjust(30,'0')
'00000000python string function'
>>.>str.ljust(30,'0')
'python string function00000000'
>>> str.center(30,'0')
'0000python string function0000'

5.字符串搜索相关
搜索指定字符串,没有返回-1:str.find('t')
指定起始位置搜索:str.find('t',start)
指定起始及结束位置搜索:str.find('t',start,end)
从右边开始查找:str.rfind('t')
搜索到多少个指定字符串:str.count('t')
上面所有方法都可用index代替,不同的是使用index查找不到会抛异常,而find返回-1

6.字符串去空格及去指定字符
去两边空格:str.strip()
去左空格:str.lstrip()
去右空格:str.rstrip()
去两边字符串:str.strip('d'),相应的也有lstrip,rstrip

7.字符串判断相关
是否以start开头:str.startswith('start')
是否以end结尾:str.endswith('end')
是否全为字母或数字:str.isalnum()
是否全字母:str.isalpha()
是否全数字:str.isdigit()
是否全小写:str.islower()
是否全大写:str.isupper()

 五.其他内置函数

1.enumerate()  .返回一个枚举类型

>>> for i,j in enumerate(('a','b','c')):
print(i,j)

0 a
1 b
2 c

>>> for i,j in enumerate([1,2,3]):
print(i,j)

0 1
1 2
2 3

>>> for i,j in enumerate('abc'):
print(i,j)

0 a
1 b
2 c

>>> for i,j in enumerate({'a':1,'b':2}):
print(i,j)

0 b
1 a

2.zip(*iterables) 生成一个迭代器,它(迭代器)聚合了从每个可迭代数集里的元素。

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]

 

posted @ 2017-04-01 22:58  视野  阅读(8775)  评论(0编辑  收藏  举报