1.常用内置函数表:

python董付国代码_迭代


python董付国代码_python董付国代码_02


python董付国代码_bc_03


python董付国代码_迭代_04


python董付国代码_迭代_05


python董付国代码_迭代_06


查看内置函数:

>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
>>> dir('a')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> help(''.center)
Help on built-in function center:

center(width, fillchar=' ', /) method of builtins.str instance
    Return a centered string of length width.

    Padding is done using the specified fill character (default is a space).

>>> help(math.sqrt)
Help on built-in function sqrt in module math:

sqrt(x, /)
    Return the square root of x.
>>> help(sum)
Help on built-in function sum in module builtins:

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

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

ord()和chr()是一对功能相反的函数
ord():用来返回单个字符的序数或Unicode码
chr():用来返回某序数对应的字符
str():则直接将任意类型的参数转换成字符串

>>> ord('A')
65
>>> chr(97)
'a'
>>> str([1,2,3])
'[1, 2, 3]'
>>> str(1234)
'1234'
>>> str((1,4,2,3))
'(1, 4, 2, 3)'
>>> str({1,2,3,4})
'{1, 2, 3, 4}'
>>> int(str(1234))
1234
>>> list(str([1,2,3,4]))
['[', '1', ',', ' ', '2', ',', ' ', '3', ',', ' ', '4', ']']
>>> eval(str([1,2,3,4]))
[1, 2, 3, 4]

max(),min(),sum()函数的用法,以及如何求均值:
#列表推导式:

>>> import random
>>> a=[random.randint(1,50) for i in range(5)]
>>> a
[1, 13, 19, 44, 50]
>>> print(max(a),min(a),sum(a))
50 1 127
>>> sum(a)/len(a)
25.4

内置函数max()和min()的key参数可以用来制定比较规则:

>>> x=['21','1234','9']
>>> max(x)
'9'
>>> max(x,key=len)
'1234'
>>> min(x,key=int)
'9'
>>> min(x,key=len)
'9'

内置函数type()和isinstance()可以判断数据类型:

>>> type([3])
<class 'list'>
>>> type(3)
<class 'int'>
>>> type((3))
<class 'int'>
>>> type((3,4))
<class 'tuple'>
>>> type({3})in (list,tuple,dict)
False
>>> type([3])in (list,int,tuple)
True
>>> type((3,4)) in (list,tuple,int)
True
>>> isinstance(3,int)
True
>>> isinstance(3j,(int,float,complex))
True

sorted()函数的功能:对列表,元组,字典,集合或其他可迭代对象进行排序并返回新列表;

>>> x=['aaaa','bc','d','b','ba']
>>> sorted(x,key=lambda item:((len(item)),item)) #先按长度排序,长度一样的正常排序
['b', 'd', 'ba', 'bc', 'aaaa']

reversed()函数的功能:对可迭代对象进行首位交换,并返回可迭代的reversed对象(生成器对象和具有惰性求值特性的zip,map,filter,enumerate等类似对象除外)

>>> reversed(x)
<list_reverseiterator object at 0x000001426ACEBB88>
>>> list(reversed(x))
['ba', 'b', 'd', 'bc', 'aaaa']

enumerate()函数用来枚举可迭代对象中的元素,返回可迭代的enumerate对象,对其中每个元素都是包含索引和值的元组。
枚举字符串和列表中的元素:

>>> list(enumerate('abcd'))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
>>> list(enumerate(['Python','Greate']))
[(0, 'Python'), (1, 'Greate')]

枚举字典中的元素:
注意,此处发现枚举的顺序和上面并不一样,这是因为字典本身是无序的,它是根据哈希值和哈希表决定的。

>>>  list(enumerate({'a':97,'b':98,'c':99}.items()))
  File "<stdin>", line 1
    list(enumerate({'a':97,'b':98,'c':99}.items()))
    ^
IndentationError: unexpected indent
>>> list(enumerate({'a':97,'b':98,'c':99}.items()))
[(0, ('a', 97)), (1, ('b', 98)), (2, ('c', 99))]

此处在运行是又出现了个小bug“IndentationError: unexpected indent”
原因是缩进问题,马虎了~
for循环(常用) 枚举range对象中的元素:

>>> for index,value in enumerate(range(10,15)):
...     print((index,value),end=' ')
...
(0, 10) (1, 11) (2, 12) (3, 13) (4, 14) >>>
>>>
>>> for index,value in enumerate(range(10,15)):
...     print((index,value),end='*')
...
(0, 10)*(1, 11)*(2, 12)*(3, 13)*(4, 14)*>>>

结束不定义的话,就是默认‘\n’.

>>> for index,value in enumerate(range(10,15)):
...     print((index,value))
...
(0, 10)
(1, 11)
(2, 12)
(3, 13)
(4, 14)

函数map() 的功能:就是说把一个函数func依次映射到序列或迭代器对象的每个元素上,并返回一个可迭代的map对象作为结果,map对象中的每个元素是原序列中的元素经过函数func处理后的结果。

>>> def add5(v):
...     return v+5
...
>>> list(map(add5,range(0,5)))
[5, 6, 7, 8, 9]

把双参数函数映射到两个序列上:

>>> def func(a,b):
...     return a*b-2
...
>>> list(map(func,range(2,6),range(5,10)))
[8, 16, 26, 38]

标准库functools中的函数reduce()可以将一个接受2个参数的函数以迭代累积的方式从做到右一次作用到一个序列或迭代器对象的元素上,并且允许指定一个初试值。
from functools import reduce先导入

>>> from functools import reduce
>>> seq=list(range(1,10))
>>> reduce(lambda x,y:x+y,seq)
45

python董付国代码_迭代_07


内置函数filter()“过滤函数”,将一个单参数函数作用到一个序列上,返回该序列中使得该函数返回值为True的那些元素组成的filter对象,如果指定函数为None,则返回序列中等价于True的元素。

>>> seq=['foo','x41','?!','***']
>>> def func(x):
...     return x.isalnum()
...
>>> filter(func,seq)
<filter object at 0x0000021A2A7C1208>
>>> list(filter(func,seq))
['foo', 'x41']

range()是Python开发中非常常用的一个内置函数,语法格式为range([start,]end[,step]) 。该函数返回值具有惰性求值特点的range对象,其中包含左闭右开区间[start,end)内以step为步长的整数。参数start默认为0,step默认为1。

>>> range(5)
range(0, 5)
>>> list(_)
[0, 1, 2, 3, 4]
>>> list(range(1,10,2))
[1, 3, 5, 7, 9]
>>> list(rangr(9,0,-2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'rangr' is not defined
>>> list(range(9,0,-2))
[9, 7, 5, 3, 1]

zip()函数,用来把多个可迭代对象的元素压缩到一起,返回一个可迭代的zip对象,其中每个元素都是包含原来的多个可迭代对象对应位置上的元素的元组,如同拉链一样~

python董付国代码_Python_08

>>> list(zip('abcd','123'))
[('a', '1'), ('b', '2'), ('c', '3')]
>>> list(zip('ab','123'))
[('a', '1'), ('b', '2')]
>>> list(zip('123','abc',',.!'))
[('1', 'a', ','), ('2', 'b', '.'), ('3', 'c', '!')]
>>> x=zip('abc','123')
>>> list(x)
[('a', '1'), ('b', '2'), ('c', '3')]

2.Python中对象的删除

  • 在Python中具有自动内存管理功能,Python解释器会自动跟踪所有的值,一旦发现某个值不再有任何变量指向,将会自动删除该值。尽管如此,自动内存管理或者垃圾回收机制并不能保证及时释放内存。显式释放自己申请的资源是程序员的好习惯之一,也是程序员素养的重要体现之一。
  • 在Python中,可以使用del命令来显式删除对象并解除与值之间的指向关系。删除对象时,如果其指向的值还有别的变量指向则不删除该值,如果删除对象后该值不再有其他变量指向,则删除该值。即接触某种指向关系~
>>> x=[1,2,3,4,5]
>>> y=3
>>> z=y
>>> print(y)
3
>>> del y
>>> print(y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>> print(z)
3
>>> del z
>>> print(z)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'z' is not defined
>>> del x[1]
>>> print(x)
[1, 3, 4, 5]
>>> del x
>>> print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

注:del不能删除元组和字符串中的元素,因为为不可变序列,只可以删除整个元组和字符串。

>>> x=(1,2,3,4)
>>> del x[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
>>> del x
>>> print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

3.基本输入输出
Python 3.x中,不存在raw_input()函数,只提供了input()函数用来接受用户的键盘输入。且在该版本下,无论user输入数据时使用什么界定符,input()函数的返回结果都是字符串,需要将其转换为相应的类型再处理~

>>> x=input('Please input:')
Please input:3
>>> print(type(x))
<class 'str'>
>>>
>>> x=input('Please input:')
Please input:'3'
>>> print(type(x))
<class 'str'>
>>>
>>> x=input('Please input:')
Please input:[1,2,3]
>>> print(type(x))
<class 'str'>
>>>
>>> x=raw_input('Please input:')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'raw_input' is not defined

默认情况下,Python将结果输出到IDLE或者标准控制台,在输出时也可以进行重定向,例如可以把结果输出到指定文件。

>>> fp=open(r'C:\Users\91908\Desktop\影评','a+')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\91908\\Desktop\\影评'
>>>
>>> fp=open(r'C:\Users\91908\Desktop\影评\1.txt','a+')
>>> print('Hello,world!',file=fp)
>>> fp.close()

此处的小bug解决方案:
1.你有可能已经打开了这个文件,关闭这个文件即可
2. open 打开一个文件夹(目录),而不是文件

此处引用某老哥的帖子:
另外,为了实现输出内容之后不换行,需要:

>>> for i in range(10,20):
...     print(i,end=' ')
...
10 11 12 13 14 15 16 17 18 19 >>>
>>> for i in range(10,20):
...     print(i)
...
10
11
12
13
14
15
16
17
18
19

模块的导入与使用:

  • from math import (sin…);
  • import math
    math.sin()

如果需要导入多个模块,一般建议按如下顺序进行导入:
标准库->成熟的第三方扩展库->自己开发的库