11-30

python内置函数

  • 内建函数的例子(自己写的绝对值函数和abs函数)
In [3]:  def fun(x):
   ...:     if x<0:
   ...:        return -x
   ...:     else:
   ...:        return x
   ...:    

In [4]: fun(-1)
Out[4]: 1

In [5]: fun(1)
Out[5]: 1

In [6]: abs(-1)
Out[6]: 1

In [7]: abs(11)
Out[7]: 11

In [8]: help(abs)
Help on built-in function abs in module builtins:

abs(x, /)
    Return the absolute value of the argument.

  • 内建的max函数
In [9]: help(max)
Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.


In [10]: max([1,2,3,4])
Out[10]: 4

In [11]: max('abcde')
Out[11]: 'e'

In [12]: max('123abcde')
Out[12]: 'e'


  • 内建len函数的使用
In [15]: help(len)
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.


In [16]: len('sldfjslj')
Out[16]: 8

In [17]: len({'a':1,'b':2})
Out[17]: 2

  • 内建的divmod函数,输出商和余数
In [18]: help(divmod)
Help on built-in function divmod in module builtins:

divmod(x, y, /)
    Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.


In [19]: divmod(3,2)
Out[19]: (1, 1)

In [20]: divmod(13,2)
Out[20]: (6, 1)

  • 内建的pow函数
In [21]: help(pow)
Help on built-in function pow in module builtins:

pow(x, y, z=None, /)
    Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
    
    Some types, such as ints, are able to use a more efficient algorithm when
    invoked using the three argument form.


In [22]: pow(2,3,5)
Out[22]: 3

  • 内建的round函数
In [23]: help(round)
Help on built-in function round in module builtins:

round(...)
    round(number[, ndigits]) -> number
    
    Round a number to a given precision in decimal digits (default 0 digits).
    This returns an int when called with one argument, otherwise the
    same type as the number. ndigits may be negative.


In [24]: round(12.345)
Out[24]: 12

In [25]: round(12.345,1)
Out[25]: 12.3

In [26]: round(12.345,2)
Out[26]: 12.35

In [27]: round(12.345,3)
Out[27]: 12.345

  • callable函数(判断是否可调用)
In [29]: a='123'

In [30]: callable(a)
Out[30]: False

In [31]: def a():
    ...:     pass
    ...: 

In [32]: callable(a)
Out[32]: True

  • type()判断类型
In [33]: type(a)
Out[33]: function

In [34]: b=(1,2)

In [35]: type(b)
Out[35]: tuple

  • isinstance函数,判断类型是不是指定的类型

In [39]: help(isinstance)
Help on built-in function isinstance in module builtins:

isinstance(obj, class_or_tuple, /)
    Return whether an object is an instance of a class or of a subclass thereof.
    
    A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
    or ...`` etc.

In [40]: a='111'

In [41]: isinstance(a,str)
Out[41]: True

In [42]: isinstance(b,tuple)
Out[42]: True

  • range函数,返回的是列表
In [46]: help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |  
 |  Return an object that produces a sequence of integers from start (inclusive)
 |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 |  These are exactly the valid indices for a list of 4 elements.
 |  When step is given, it specifies the increment (or decrement).
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)


In [47]: range(5)
Out[47]: range(0, 5)

In [48]: a=range(5)

In [49]: for i in a:
    ...:     print(i)
    ...:     
0
1
2
3
4

类型转换函数

  • int()转换成int类型
In [52]: help(int)
Help on class int in module builtins:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |  
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |  
 |  Methods defined here:
 |  
 |  __abs__(self, /)
 |      abs(self)
 |  
 |  __add__(self, value, /)


In [53]: int(1.2)
Out[53]: 1

In [54]: int(1.233)
Out[54]: 1

In [55]: int('123')
Out[55]: 123

  • long函数,str函数,float函数都和int函数转换方法一样的

  • eval函数,当字符串变成有效的表达式求值


In [58]: help(eval)
Help on built-in function eval in module builtins:

eval(source, globals=None, locals=None, /)
    Evaluate the given source in the context of globals and locals.
    
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

In [62]: eval('1 > 2')
Out[62]: False

In [63]: eval('0x18')
Out[63]: 24


  • chr(),返回参数的ascii码的字符
In [64]: help(chr)
Help on built-in function chr in module builtins:

chr(i, /)
    Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.


In [65]: chr(1)
Out[65]: '\x01'

In [66]: chr(100)
Out[66]: 'd'

In [67]: chr(97)
Out[67]: 'a'

In [68]: chr(65)
Out[68]: 'A'

## 字符串处理的函数

  • str.capitalize(),首字母变成大写
In [72]: a='abc'

In [73]: a.capitalize()
Out[73]: 'Abc'


In [74]: help(a.capitalize)
Help on built-in function capitalize:

capitalize(...) method of builtins.str instance
    S.capitalize() -> str
    
    Return a capitalized version of S, i.e. make the first character
    have upper case and the rest lower case.

  • str.replace(),字符串的替换
In [74]: help(a.replace)
Help on built-in function replace:

replace(...) method of builtins.str instance
    S.replace(old, new[, count]) -> str
    
    Return a copy of S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.


In [75]: a.replace('a','b')
Out[75]: 'bbc'

  • a.split(),指定字符切割
In [76]: help(a.split)
Help on built-in function split:

split(...) method of builtins.str instance
    S.split(sep=None, maxsplit=-1) -> list of strings
    
    Return a list of the words in S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.


In [77]: a.split('b')
Out[77]: ['a', 'c']

  • join(),列表转换成字符串
In [78]: help(''.join)
Help on built-in function join:

join(...) method of builtins.str instance
    S.join(iterable) -> str
    
    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

In [83]: ''.join([str(i) for i in range(5)])
Out[83]: '01234'


序列的处理函数

  • filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
    该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

In [93]: def fun(x):
    ...:     return x%2==1
    ...: 

In [94]: filter(fun,range(10))
Out[94]: <filter at 0x7f62bc0c9ef0>

In [95]: aa=filter(fun,range(10))

In [96]: for i in aa:
    ...:     print(i)
    ...:     
1
3
5
7
9


  • zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
In [97]: a=['a','b']

In [98]: b=[1,2,3]

In [99]: zip(a,b)
Out[99]: <zip at 0x7f62bc04b848>

In [100]: aa=zip(a,b)

In [101]: aa
Out[101]: <zip at 0x7f62bd6f7a08>

In [102]: for i in aa:
     ...:     print(i)
     ...:     
('a', 1)
('b', 2)

  • map() 会根据提供的函数对指定序列做映射。
In [111]: def fun(x):
     ...:     return x*x
     ...: 

In [112]: map(fun,range(4))
Out[112]: <map at 0x7f62bc0c3fd0>

In [113]: for i in map(fun,range(4)):
     ...:     print(i)
     ...:     
0
1
4
9

In [114]: def fun(x,y):
     ...:     return x+y
     ...: 

In [115]: aa=map(fun,range(4),range(4))

In [116]: for i in aa:
     ...:     print(i)
     ...:     
0
2
4
6

  • reduce()函数
reduce(...)
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

In [117]: from functools import reduce

In [118]: def add(x,y):
     ...:     return x+y
     ...: 

In [119]: print(reduce(add,range(1,101)))
5050

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值