Python内建函数

 

abs()

abs函数接收一个数字对象,返回它的绝对值,如果接受的对象不是数字抛出TypeError异常

abs(...)
    abs(number) -> number
    
    Return the absolute value of the argument.
help(abs)
>>> abs(-1)
1
>>> abs(1)
1
>>> abs('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'
View Code

divmod()

接收两个init对象,返回它们的商数、余数作为一个元组
divmod
>>> divmod(99,8)
(12, 3)
View Code

all()

接收一个可迭代的对象,如果这个可迭代对象所有元素bool值为真则返回True,否则返回False

all(...)
    all(iterable) -> bool
    
    Return True if bool(x) is True for all values x in the iterable.
    If the iterable is empty, return True.
help(all)
>>> iter1 = (1,2,3,4)
>>> iter2 = [1,2,3,False,None]
>>> all(iter1)
True
>>> all(iter2)
False
View Code

等价于

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

any()

接收一个可迭代对象,如果这个可迭代的对象任一元素为真则返回True,否则返回False

any(...)
    any(iterable) -> bool
    
    Return True if bool(x) is True for any x in the iterable.
    If the iterable is empty, return False.
any
>>> iter1 = (1,2,None)
>>> iter2 = [False,None]
>>> any(iter1)
True
>>> any(iter2)
False
View Code

等价于

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
View Code

int()

将对象转换为整数型,如果没有参数返回0,如果是float对象,则只返回整数部分
>>> int()
0
>>> int('123')
123
>>> int(123)
123
>>> int(123.123)
123
>>> int(-123)
-123
>>> int('-123')
-123
View Code

long()

转成长整型,python3废弃

>>> long(100)
100L
>>> long(0)
0L
>>> long('100')
100L
View Code

hex()

将任意大小的整数转化成以“0x”打头的小写的十六进制字符串,例如
hex(...)
    hex(number) -> string
    
    Return the hexadecimal representation of an integer or long integer.
help(hex)
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
>>> hex(1L)
'0x1L'
View Code

pow(x, y[, z])

返回x 的 y次幂; 如果 z 提供的时候,, 返回 x 的 y 次幂,然后对z相除取余
pow(...)
    pow(x, y[, z]) -> number
    
    With two arguments, equivalent to x**y.  With three arguments,
    equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
help(pow)
>>> pow(2,3)
8
>>> pow(2,3,3)
2

sum(iterable[, start])

接收一个可迭代的对象,求和,star默认标志是0,如果是整数则一起相加(必须是一个整型)
>>> sum([1,2,3,4])
10
>>> sum([1,2,3,4],2)
12
>>> sum([1,2,3,4],-1)
9
help(sum)
>>> sum([1,2,3,4])
10
>>> sum([1,2,3,4],2)
12
>>> sum([1,2,3,4],-1)
9

basestring()

用来测试一个对象是否是str或者unicode的实例。 isinstance(obj, basestring)等同于isinstance(obj, (str, unicode)),python3废弃
>>> a = 'string'
>>> isinstance(a,basestring)
True
>>> isinstance(123,basestring)
False
help(basestring)
>>> a = 'string'
>>> isinstance(a, basestring)
True
>>> isinstance(123, basestring)
False
View Code

cmp(x, y)

比较两个对象x和y,根据结果返回一个整数。如果x < y,返回负数;如果x == y,返回0;如果x > y,返回正数
>>> cmp(1,2)
-1
>>> cmp(2,2)
0
>>> cmp(3,2)
1
>>> cmp('a','A')
1
>>> cmp('A','a')       #字符串比acsii码
-1
>>> cmp('A','B')
-1
>>> cmp('A','BC')
-1

zip(seq1 [, seq2 [...]])

zip函数接收若干个序列,一一对应生成一个列表,包含元组对

Help on built-in function zip in module __builtin__:

zip(...)
    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
    
    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is truncated
    in length to the length of the shortest argument sequence.
help(zip)
>>> zip('ab','12')
[('a', '1'), ('b', '2')]
>>> zip('ab','12','c4')
[('a', '1', 'c'), ('b', '2', '4')]
>>> seq1 = ['Michael','Lucy','Linda','Jason']
>>> seq2 = [70,90,85,60]
>>> reslut = zip(seq1,seq2) 
>>> print reslut                            # 两个列表一一对应生成一个元组对,放在一个列表中
[('Michael', 70), ('Lucy', 90), ('Linda', 85), ('Jason', 60)]
>>> 
>>> print dict(reslut)                                    # dict变成一个字典     
{'Linda': 85, 'Michael': 70, 'Lucy': 90, 'Jason': 60}

小结:如果两个序列需要一一对应生成字典,用zip函数和dict函数,如果不是对应的则只会对应相关.

sorted(iterable, cmp=None, key=None, reverse=False)

接收一个可迭代的对象,进行排序

Help on built-in function sorted in module __builtin__:

sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
help(sorted)
>>> alit = [1,3,4,2,9,3,2,2]
>>> sorted(alit)
[1, 2, 2, 2, 3, 3, 4, 9]              #升序,从小到到

>>> sorted(alit,reverse=True)  #降序,从大到小
[9, 4, 3, 3, 2, 2, 2, 1]

之外,还可以给字典排序,假设有如下嵌套的dict

info = {
    1: {
        'name': 'sam',
        'age': 10, 
        'city': 'guangzhou'
    },
   2: {
        'name': 'allen',
        'age': 21,
        'city': 'beijin'
    },
   3: {
        'name': 'alice',
        'age': 26,
        'city': 'beijin'
    },
    4: {
        'name': 'tom',
        'age': 18,
        'city': 'shenzhen'
    }
}

按照年龄排序( 升序 、降序)

>>> sorted(info.items(), key=lambda x: x[1]['age'])                 # 从小到大(升序)
[(1, {'city': 'guangzhou', 'age': 10, 'name': 'sam'}), (4, {'city': 'shenzhen', 'age': 18, 'name': 'tom'}), (2, {'city': 'beijin', 'age': 21, 'name': 'allen'}), (3, {'city': 'beijin', 'age': 26, 'name': 'alice'})]

>>> sorted(info.items(), key=lambda x: x[1]['age'], reverse=True) # 从大到小(降序) [(3, {'city': 'beijin', 'age': 26, 'name': 'alice'}), (2, {'city': 'beijin', 'age': 21, 'name': 'allen'}), (4, {'city': 'shenzhen', 'age': 18, 'name': 'tom'}), (1, {'city': 'guangzhou', 'age': 10, 'name': 'sam'})]

小结:sorted可以给itetabler排序

isinstance()

判断一个对象的类型、或是不是某个类的子类等,返回bool. 判断一个类型应该建议使用isinstance(), 而不是type()

Help on built-in function isinstance in module __builtin__:

isinstance(...)
    isinstance(object, class-or-type-or-tuple) -> bool
    
    Return whether an object is an instance of a class or of a subclass thereof.
    With a type as second argument, return whether that is the object's type.
    The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
    isinstance(x, A) or isinstance(x, B) or ... (etc.).
help(isinstance)
>>> a = 123
>>> astr = 'string'
>>> b = 1.23
>>> isinstance(a,int)
True
>>> isinstance(a,(int,float))
True

判断一个对象是否为iterable

>>> from collections import Iterable
>>> a = [1,2,3]
>>> isinstance(a,Iterable)
True
>>> isinstance(123,Iterable)
False
View Code

判断一个对象是否为iterator

>>> from collections import Iterator
>>> isinstance('abc', Iterator)
False
>>> isinstance(123, Iterator)
False
>>> isinstance(iter('abc'), Iterator)
True
View Code

iterable不同等于iterator, 但是都可以迭代, 可以使用iter函数将iterable变成iterator

issubclass(C, B)

用于检测类的继承关系、一个类是另一类的子类

>>> issubclass(bool, int)    # bool对象是int的子类
True
>>> class Person():
... pass
... 
>>> class ChildPerson(Person):
... pass
... 
>>> issubclass(ChildPerson, Person)
True
View Code

reversed(sequence)

接收一个序列型的对象,对这个对象进行反转,并作为一个迭代器返回

a = [1,2,5,7,9]
b = reversed(a)    

print b                    # 表明是一个可迭代的对象
for x in b:
    print x

<listreverseiterator object at 0x0000000001DA39E8>
9
7
5
2
1
View Code

如果一个序列型对象很大要进行反转,可以用reversed()函数

locals()

更新并返回当前范围的本地(局部)变量命名空间字典,返回一个dict.  简单说就是用来看局部的命名空间.

locals(...)
    locals() -> dictionary
    
    Update and return a dictionary containing the current scope's local variables.
help(local)
def myfunc(x, y):
    """docstring for the myfunc"""
    z = 10 
    h = 10
    print locals()
myfunc(10, 20)

{'y': 20, 'h': 10, 'z': 10, 'x': 10}
View Code

globals()

全局命名空间字典, 返回一个dict

globals(...)
    globals() -> dictionary
    
    Return the dictionary containing the current scope's global variables. 

返回一个dict,包含当前命名空间里所有的全局变量
help(globals)
>>> a = '123'
>>> def func_one(x, y):
...     return x + y
... 
>>> print globals()
{'a': '123', '__builtins__': <module '__builtin__' (built-in)>, 
'__package__': None, 'sys': <module 'sys' (built-in)>, 
'atexit': <module 'atexit' from '/usr/local/lib/python2.7/atexit.pyc'>,
 '__name__': '__main__',
 'func_one': <function func_one at 0x7fd3862a8c08>, '__doc__': None} 

vars([object])

vars
print vars()                        # 没有参数等同于locals()的功能, 返回局部的命名空间字典

def func(x=10, y=10):
    print vars()         
    return x + y

print func()

{'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'E:\\NOTE\\python\\learnpython\\code\\_weblogic.py', '__package__': None, '__name__': '__main__', 'os': <module 'os' from 'C:\Python27\lib\os.pyc'>, '__doc__': None}          # 1
{'y': 10, 'x': 10}           # 2
20
import time

print vars(time)               # 如果有参数对象, 则等同于对象.__dict__的功能(如果有__dict__属性)

frozenset()

不可变、无序不重复的集合

它和set集合类似,除了不可变之外其它功能和set一样, 就像list和tuple的一样

class frozenset(object)
 |  frozenset() -> empty frozenset object
 |  frozenset(iterable) -> frozenset object
 |  
 |  Build an immutable unordered collection of unique elements.
 |  
 |  Methods defined here:
 |  
 |  __and__(...)
 |      x.__and__(y) <==> x&y
 |  
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x.
 |  
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |  
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |  
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |  
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |  
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |  
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |  
 |  __or__(...)
 |      x.__or__(y) <==> x|y
 |  
 |  __rand__(...)
 |      x.__rand__(y) <==> y&x
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  __ror__(...)
 |      x.__ror__(y) <==> y|x
 |  
 |  __rsub__(...)
 |      x.__rsub__(y) <==> y-x
 |  
 |  __rxor__(...)
 |      x.__rxor__(y) <==> y^x
 |  
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |  
 |  __sub__(...)
 |      x.__sub__(y) <==> x-y
 |  
 |  __xor__(...)
 |      x.__xor__(y) <==> x^y
 |  
 |  copy(...)
 |      Return a shallow copy of a set.
 |  
 |  difference(...)
 |      Return the difference of two or more sets as a new set.
 |      
 |      (i.e. all elements that are in this set but not the others.)
 |  
 |  intersection(...)
 |      Return the intersection of two or more sets as a new set.
 |      
 |      (i.e. elements that are common to all of the sets.)
 |  
 |  isdisjoint(...)
 |      Return True if two sets have a null intersection.
 |  
 |  issubset(...)
 |      Report whether another set contains this set.
 |  
 |  issuperset(...)
 |      Report whether this set contains another set.
 |  
 |  symmetric_difference(...)
 |      Return the symmetric difference of two sets as a new set.
 |      
 |      (i.e. all elements that are in exactly one of the sets.)
 |  
 |  union(...)
 |      Return the union of sets as a new set.
 |      
 |      (i.e. all elements that are in either set.)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T
frozenset
>>> frozen_set = frozenset()                                       # 创建一个空的frozenset集合
>>> frozen_set
frozenset([])
>>> 
>>> frozen_set2 = frozenset('abcdefghigkomnopqrszuvwxyz')          # 从一个str创建一个frozenset集合
>>> frozen_set2
frozenset(['a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'k', 'm', 'o', 'n', 'q', 'p', 's', 'r', 'u', 'w', 'v', 'y', 'x', 'z'])     
>>> 
>>> frozen_set2 = frozenset(['a','b','c','d','e'])                 # 从一个list创建一个frozenset集合
>>> frozen_set2
frozenset(['a', 'c', 'b', 'e', 'd'])

应用场景: 如果要创建和使用一个不会修改的集合可以用frozenset

hash(object)

hash函数接收一个对象返回的它的hash值 (整形), 只有不可变的对象可以进行hash运算,否则抛出unhashable异常

hash(...)
    hash(object) -> integer
    
    Return a hash value for the object.  Two objects with the same value have
    the same hash value.  The reverse is not necessarily true, but likely.
hash
>>> hash(100)
100
>>> hash((1,2,3,4))
485696759010151909
>>> 
>>> hash('abc')
1453079729188098211
>>>
>>> hash([1,2,3,4])                  # list是可变的对象, 所以hash运算会抛出异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list' 
View Code

callable

判断对象是否可以被调用, 返回bool

callable(obj, /)
    Return whether the object is callable (i.e., some kind of function).
    
    Note that classes are callable, as are instances of classes with a
    __call__() method.
callable
def func():
  pass

f2 = 100

class TestClass(object):
  pass

print(callable(func))         # True   函数可以被调用
print(callable(f2))           # False  int类型不可以被调用
print(callable(TestClass))    # True   类可以被调用 
View Code

dir

返回对象的属性(字符串)组成的list

如果没有给出参数,则返回当前作用域中的名字(相当于globals函数),否则获取指定对象的属性(按字母的顺序排列).

如果对象有__dir__方法,则按照__dir__方法的结果返回.

对于模块对象,返回模块的属性

对于类对象,返回它的属性以及递归方式获取其父类(如果有)的属性

对于任何其他对象:返回本身的属性,所属类的属性,和递归方式获取其基类(如果有)的属性

dir(...)
    dir([object]) -> list of strings   返回由对象的属性组成的list
    
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.
dir

slice

slice是切片函数,可以用它保留切片的范围,直接引用,用法:

slice(start, stop[, step])       # 起始、结束、步长
>>> s = slice(1,5)
>>> s.start, s.stop, s.step      # 起始、结束、步长
(1, 5, None)

当进行大量切片的操作时候可以把切片的范围保留起来,进行切片

>>> l = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
常规的切片动作,比较繁琐
>>> l[5:20:3]
'filor'
>>> l[5:14:2]
'fhjln'
>>> l[12:20:4]
'mr'
>>> 
定义好切片的范围,直接引用
>>> s1 = slice(5, 20, 3)
>>> s2 = slice(5, 14, 2)
>>> s3 = slice(12, 20, 5)
>>> 
>>> l[s1]
'filor'
>>> l[s2]
'fhjln'
>>> l[s3]
'mr'
View Code

 

posted @ 2016-07-25 20:05  opss  阅读(316)  评论(0编辑  收藏  举报