python3.x 基础二:内置函数

自带的函数可以非常简单快捷的实现某些功能,

比如产生一个序列,可以用循环实现:

count = 0
while count < 10:
    print(count)
    count+=1
View Code

但其实用range会更简单:

for i in range(10):
    print(i)
View Code

 

在python命令行下查看帮助:

help()

help> str

或者

help(str)

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

  • 返回绝对值
>>> print(abs(10))
10
>>> print(abs(-10))
10
>>> print(abs(10.5)) 10.5 >>> print(abs(-10.5)) 10.5
  • 复数,此方法返回此复数的绝对值(此复数与它的共轭复数的乘积的平方根)--基本用不上了,复数在工程领域使用

 2.all(iterable, /)
    Return True if bool(x) is True for all values x in the iterable.
    If the iterable is empty, return True.

  •  全部元素为真,则为真,否则为假
>>> all([-1,0,1])
False

3.any(iterable, /)
    Return True if bool(x) is True for any x in the iterable.
    If the iterable is empty, return False.

  • 一个为真,,则为真,否则为假
>>> any([-1,0,1])
True

4.ascii(obj, /) 同repr()

    Return an ASCII-only representation of an object.

  • 返回可打印对象的字符串表示
>>> ascii(100)
'100'
>>> ascii('100')
"'100'"
>>> ascii('abcd')
"'abcd'"
>>> ascii('水电费水电费')
"'\\u6c34\\u7535\\u8d39\\u6c34\\u7535\\u8d39'"

5.bin(number, /)

    Return the binary representation of an integer.

  • 返回整形的二进制
>>> bin(1)
'0b1'
>>> bin(255)
'0b11111111'

 6.|  bool(x) -> bool

  • 返回真假,1为真,0 为假,空为假
View Code

7.bytearrayclass bytearray(object)
 |  bytearray(iterable_of_ints) -> bytearray
 |  bytearray(string, encoding[, errors]) -> bytearray
 |  bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
 |  bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
 |  bytearray() -> empty bytes array

  • 把二进制变成一个可修改的列表
>>> b=bytearray('abcd',encoding='utf-8')
>>> b[0]
97
>>> b
bytearray(b'abcd')
>>> b[1]
98
>>> b[1]='B'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> b[1]=100
>>> b
bytearray(b'adcd')
>>> b[1]=200
>>> b
bytearray(b'a\xc8cd')

8.bytes

class bytes(object)
 |  bytes(iterable_of_ints) -> bytes
 |  bytes(string, encoding[, errors]) -> bytes
 |  bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
 |  bytes(int) -> bytes object of size given by the parameter initialized with null bytes
 |  bytes() -> empty bytes object

  • 字符串不可修改,做的各种操作都会新开辟一个内存空间
>>> ascii('水电费水电费')
"'\\u6c34\\u7535\\u8d39\\u6c34\\u7535\\u8d39'" >>> a=bytes('abcd',encoding='utf-8') >>> print(a.upper(),a) b'ABCD' b'abcd'
  • 不写参数,返回长度为0的字节数组
>>> bytes()
b''
>>> print(bytes())
b''
>>> len(bytes()) 0 >>> print(type(len(bytes()))) <class 'int'>
  • source为字符串时,必须编码,并使用str.encode()转换成字节数组
>>> bytes('asdf','utf-8') b'asdf' >>> bytes('水电费','utf-8') b'\xe6\xb0\xb4\xe7\x94\xb5\xe8\xb4\xb9'

9.callable(obj, /)
    Return whether the object is callable (i.e., some kind of function).

  • 返回一个对象是否可调用
>>> def func():
...     print('aa')
... 
>>> callable(func)
True

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

  • 返回ASCII码对应的字符
>>> chr(97)
'a'

11.ord(c, /)
    Return the Unicode code point for a one-character string.

  • 返回ASCII值,只能传入1个字符
>>> ord('a')
97
>>> ord('1') 49 >>> ord('A') 65 >>> ord('10000') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ord() expected a character, but string of length 5 found

12.compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
    Compile source into a code object that can be executed by exec() or eval().

  • exec(code),远程执行一段代码
code='''
def fib(n):
    if n==0:
        return 0
    elif n ==1 or n ==2:
        return 1
    return fib(n-1)+fib(n-2)
print(fib(10))
'''
exec(code)

13.class dict(object)
 |  dict() -> new empty dictionary

  • 字典构造函数

14.dir(...)
    dir([object]) -> list of strings
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attribut

  • 返回一个对象的所有属性列表

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

  • 返回被除数的商和余数
>>> divmod(10,3)
(3, 1)

16.eval(source, globals=None, locals=None, /)
    Evaluate the given source in the context of globals and locals.

  • 返回字符串的运算结果,只能是简单的
>>> eval('1+2*3')
7

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

  • 过滤返回迭代器为true的所需要元素
>>> res=filter(lambda n:n>5,range(10))
>>> print(res)
<filter object at 0x7f192a00e240>
>>> for i in res:
...     print (i)
... 
6
7
8
9

18.class frozenset(object)
 |  frozenset() -> empty frozenset object
 |  frozenset(iterable) -> frozenset object

  • 将一个集合冻结不可修改
>>> set1=set([1,1,2,2,3,3])
>>> set1
{1, 2, 3}
>>> dir(set1)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
>>> set2=frozenset(set1)
>>> dir(set2)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union']

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

  • 返回当前程序的所有全局变量k/v

20.hash(obj, /)
    Return the hash value for the given object.

  • 返回哈希值

21.hex(number, /)
    Return the hexadecimal representation of an integer.

>>> hex(1)
'0x1'
>>> hex(10)
'0xa'
>>> hex(255)
'0xff'

22.正常数字字符串是可以转换成整型的

View Code
  • float,返回浮点型

23.isinstance(obj, class_or_tuple, /)
    Return whether an object is an instance of a class or of a subclass thereof.

  • 判断对象是否是类或者其他实例
  • 判断迭代器或者迭代类型

24.iter(...)
    iter(iterable) -> iterator
    iter(callable, sentinel) -> iterator

  • 将一个可迭代对象转换为迭代器

25.len(obj, /)

Return the number of items in a container.

  • 返回对象的长度(没看明白/表示什么意思)
>>> count_str=len('abcd')
>>> count_tuple=len((1,2,3,4,5))
>>> count_list=len([1,2,3,4,5]) >>> count_dict=len({'a':1,'b':2,'c':3}) >>> count_set=len({1,2,3,4,5}) >>> print(count_str,count_tuple,count_list,count_dict,count_set) 4 5 5 3 5 >>> 
  • 整型或者浮点型的不可以直接计算长度,否则报错
>>> len(123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module> TypeError: object of type 'int' has no len() >>> len(123.1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'float' has no len()

26.class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  

  • 可以返回空列表
  • 可以将字符串/元组/range对象转换成列
View Code

27.locals()
    Return a dictionary containing the current scope's local variables.

  • globals

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

  • 将可迭代类型元素应用到func函数

 

>>> res=map(lambda x:x*2,range(5))
>>> print(res)
<map object at 0x7f192a00e1d0>
>>> for i in res:
...     print(i)
... 
0
2
4
6
8

 

29.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.

  • 为数字则返回最大值
  • 为字符,则返回ASCII值大者
>>> max(1,2,3,4)
4
>>> max('a','b','c')
'c'
>>> max('a','A')
'a'
  • min()同理

30.oct(number, /)
    Return the octal representation of an integer.

  • 将一个整数转换为八进制

 

>>> oct(1)
'0o1'
>>> oct(8)
'0o10'
>>> oct(9)
'0o11'

 

31pow(x, y, z=None, /)
    Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

  • 求幂
>>> pow(3,3)
27
>>> pow(2,8)
256

32.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).

range(10)

  • 表示0,1,2,3,4,5,6,7,8,9序列,等价于range(0,10)或者range(0,10,1)
  • object需要为正整数,为负或者浮点数将不会得到你想要的结果
  • 默认增加步长为1,不包括停止位
  • 步长为正表示增加,为负表示减少
View Code

33.class reversed(object)
 |  reversed(sequence) -> reverse iterator over values of the sequence

  • 将一个序列翻转
>>> for i in reversed(range(10)):
...     print(i)
... 
9
8
7
6
5
4
3
2
1
0

34.round(...)
    round(number[, ndigits]) -> number

  • 1个参数下返回整形
  • 带指定小数位数时,四舍五入并返回与源数字一样的的类型
>>> round(1,2)
1
>>> round(1.1111,2)
1.11
>>> round(1.999,2)
2.0

36.sorted(iterable, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.

>>> a={1:2,2:5,6:1,-1:0}
>>> a
{1: 2, 2: 5, -1: 0, 6: 1}
>>> sorted(a)
[-1, 1, 2, 6]
>>> sorted(a.items)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is not iterable
>>> sorted(a.items())
[(-1, 0), (1, 2), (2, 5), (6, 1)]
默认按照key排序
>>> sorted(a.items(),key=lambda i:i[1]) [(-1, 0), (6, 1), (1, 2), (2, 5)]
#指定按照value排序

37.class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.

  • 将其他数据类型转换成字
  • 比如上面的求整型/浮点型长度的时候可以先转换成字符
View Code

38.sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

  • 求和,条件是可迭代类型对象
View Code

39.class type(object)
 |  type(object_or_name, bases, dict)
 |  type(object) -> the object's type
 |  type(name, bases, dict) -> a new type

  • 返回对象的类型,字典/列表取值可以辅助分析

 

40.class zip(object)
 |  zip(iter1 [,iter2 [...]]) --> zip object
 | 
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.

  • 返回一个元组
>>> list1=['a','b','c','d','e','f']
>>> list2=[1,2,3,4]
>>> zip(list1,list2)
<zip object at 0x7f1927411ac8>
>>> print(zip(list1,list2))
<zip object at 0x7f19276a1548>>>> for i in zip (list1,list2):
...     print(i)
... 
('a', 1)
('b', 2)
('c', 3)
('d', 4)
>>> 

41.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.

  • function 必须是二元函数,在省略第三个参数的情况下,函数先对 iterable 中的第1,2个数据进行操作,得到的结果再与第三个数据用 function() 函数运算……依次类推,最后得到一个结果。如果初始值 initializer 给定,第一次调用会是 initializer 和第一个元素而不是序列的头两个元素。
>>> functools.reduce(lambda x,y:x+y,range(1,5))
10
>>> functools.reduce(lambda x,y: x+y, [1,2,3,4,5], 10)
25

参考link:http://blog.csdn.net/lisonglisonglisong/article/details/38960341

 

 

 

 

 

 

 

 

>>> res=map(lambda x:x*2,range(5))
>>> print(res)
<map object at 0x7f192a00e1d0>
>>> for i in res:
...     print(i)
...
0
2
4
6
8

转载于:https://www.cnblogs.com/jenvid/p/7798642.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值