python基础,python基础语法,1、range(nu
python基础,python基础语法,1、range(nu
1、range(num)函数,返回0到num-1的列表>>> list = range(100)>>> print(list)range(0, 100)>>> print(type(list))<class ‘range‘>>>>
xxxxxxxxxx61
>>> list = range(100)2
>>> print(list)3
range(0, 100)4
>>> print(type(list))5
<class ‘range‘>6
>>>
>>> for i in range(100):... sum = sum + i + 1...>>> print(sum)5050
xxxxxxxxxx51
>>> for i in range(100):2
... sum = sum + i + 13
...4
>>> print(sum)5
5050
2、参数传递在python中,有以下几种参数传递方式:位置传递关键字传递参数默认值包裹传递(packing) vs 解包裹(unpacking)
混合传递时原则:先位置,后关键字,包裹位置,包裹关键字
位置传递:
>>> def f(a,b,c):... return a+b+c...>>> print(f(1,2,3));6
xxxxxxxxxx51
>>> def f(a,b,c):2
... return a+b+c3
...4
>>> print(f(1,2,3));5
6
关键字传递:
>>> def f(a,b,c):... return a+b+c...>>> print(f(a=1,b=2,c=3));6
xxxxxxxxxx51
>>> def f(a,b,c):2
... return a+b+c3
...4
>>> print(f(a=1,b=2,c=3));5
6
默认参数值:
>>> def f1(a,b,c=10):... return a+b+c;...>>> print(f1(1,2))13>>> print(f1(5,2))17>>> print(f1(2,4,5))11>>> print(f1(b=6))17
xxxxxxxxxx111
>>> def f1(a,b,c=10):2
... return a+b+c;3
...4
>>> print(f1(1,2))5
136
>>> print(f1(5,2))7
178
>>> print(f1(2,4,5))9
1110
>>> print(f1(b=6))11
17
包裹传递:一个星号表示传入元组、两个星号表示传入字典
>>> def func(*name):... print(type(name))... print(name)...>>> func(1,2)<class ‘tuple‘>(1, 2)>>> func(1,2,4,5,6)<class ‘tuple‘>(1, 2, 4, 5, 6)
xxxxxxxxxx101
>>> def func(*name):2
... print(type(name))3
... print(name)4
...5
>>> func(1,2)6
<class ‘tuple‘>7
(1, 2)8
>>> func(1,2,4,5,6)9
<class ‘tuple‘>10
(1, 2, 4, 5, 6)
>>> def func1(**name):... print(type(name))... print(name)...>>> func1(a=1,b=2,c=3)<class ‘dict‘>{‘a‘: 1, ‘b‘: 2, ‘c‘: 3}>>> func1(1,2,3)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: func1() takes 0 positional arguments but 3 were given
xxxxxxxxxx111
>>> def func1(**name):2
... print(type(name))3
... print(name)4
...5
>>> func1(a=1,b=2,c=3)6
<class ‘dict‘>7
{‘a‘: 1, ‘b‘: 2, ‘c‘: 3}8
>>> func1(1,2,3)9
Traceback (most recent call last):10
File "<stdin>", line 1, in <module>11
TypeError: func1() takes 0 positional arguments but 3 were given
解包裹传递:
>>> def func3(a,b,c):... print(a,b,c)...>>> a = (1,3,5)>>> func3(*a)1 3 5
xxxxxxxxxx61
>>> def func3(a,b,c):2
... print(a,b,c)3
...4
>>> a = (1,3,5)5
>>> func3(*a)6
1 3 5
>>> def func3(a,b,c):... print(a,b,c)...>>> b = {"a":"10","b":"20","c":"30"}>>> func3(**b)10 20 30
xxxxxxxxxx61
>>> def func3(a,b,c):2
... print(a,b,c)3
...4
>>> b = {"a":"10","b":"20","c":"30"}5
>>> func3(**b)6
10 20 30
3、函数对象(lambda函数)lambda函数语法:
lambda a, b : a + blambda 参数 : 方法体
xxxxxxxxxx21
lambda a, b : a + b2
lambda 参数 : 方法体
>>> func = lambda a, b : a + b>>> def sum(f,a,b):... print("--- the sum function ---")... print(f(a,b))...>>>>>> sum(func,10,20)--- the sum function ---30>>>
xxxxxxxxxx101
>>> func = lambda a, b : a + b2
>>> def sum(f,a,b):3
... print("--- the sum function ---")4
... print(f(a,b))5
...6
>>>7
>>> sum(func,10,20)8
--- the sum function ---9
3010
>>>
4、内置函数:type() 查看变量类型dir() 查看变量有哪些方法
>>> b = {"a":"1234"}>>>>>> dir(b)[‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘clear‘, ‘copy‘, ‘fromkeys‘, ‘get‘, ‘items‘, ‘keys‘, ‘pop‘, ‘popitem‘, ‘setdefault‘, ‘update‘, ‘values‘]
xxxxxxxxxx101
>>> b = {"a":"1234"}2
>>>3
>>> dir(b)4
[‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘5
, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘,6
‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘7
__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__seta8
ttr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘clear‘, ‘co9
py‘, ‘fromkeys‘, ‘get‘, ‘items‘, ‘keys‘, ‘pop‘, ‘popitem‘, ‘setdefault‘, ‘update10
‘, ‘values‘]
help()len() 长度open() 文件输入和输出
循环相关range() enumerate()zip()
iter() 循环对象
>>> list = [1,2,3,4];>>> i = iter(list)>>> i.__next__()1>>> i.__next__()2>>> i.__next__()3>>> i.__next__()4>>> i.__next__()Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration>>>
xxxxxxxxxx151
>>> list = [1,2,3,4];2
>>> i = iter(list)3
>>> i.__next__()4
15
>>> i.__next__()6
27
>>> i.__next__()8
39
>>> i.__next__()10
411
>>> i.__next__()12
Traceback (most recent call last):13
File "<stdin>", line 1, in <module>14
StopIteration15
>>>
map() 函数是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。
如:处理数值,例如,对于list [1, 2, 3, 4, 5, 6, 7, 8],如果希望把list的每个元素都作平方,就可以用map()函数:
>>> num_list = [1,2,3,4,5,6,7,8]>>> func = lambda x : x*x>>> num_map = map(func,num_list)>>> print(list(num_map))[1, 4, 9, 16, 25, 36, 49, 64]
xxxxxxxxxx51
>>> num_list = [1,2,3,4,5,6,7,8]2
>>> func = lambda x : x*x3
>>> num_map = map(func,num_list)4
>>> print(list(num_map))5
[1, 4, 9, 16, 25, 36, 49, 64]
如:处理字符串,假设用户输入的英文名字不规范,没有按照首字母大写,后续字母小写的规则,请利用map()函数,把一个list(包含若干不规范的英文名字)变成一个包含规范英文名字的list:输入:[‘adam‘, ‘LISA‘, ‘barT‘]
输出:[‘Adam‘, ‘Lisa‘, ‘Bart‘]
>>> str_list = [‘adam‘, ‘LISA‘, ‘barT‘];>>> func = lambda x : x[0:1].upper() + x[1:].lower();>>> str_map = map(func,str_list);>>> print(list(str_map));[‘Adam‘, ‘Lisa‘, ‘Bart‘]
xxxxxxxxxx51
>>> str_list = [‘adam‘, ‘LISA‘, ‘barT‘];2
>>> func = lambda x : x[0:1].upper() + x[1:].lower();3
>>> str_map = map(func,str_list);4
>>> print(list(str_map));5
[‘Adam‘, ‘Lisa‘, ‘Bart‘]
filter() 函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。例如:删除 None 或者空字符串:
>>> str_list = [‘test‘, None, ‘‘, ‘str‘, ‘ ‘, ‘END‘]>>> def is_not_empty(s):... return s and len(s.strip()); # and前的s用来排除None...>>> rs = filter(is_not_empty,str_list)>>> print(list(rs))[‘test‘, ‘str‘, ‘END‘]
xxxxxxxxxx71
>>> str_list = [‘test‘, None, ‘‘, ‘str‘, ‘ ‘, ‘END‘]2
>>> def is_not_empty(s):3
... return s and len(s.strip()); # and前的s用来排除None4
...5
>>> rs = filter(is_not_empty,str_list)6
>>> print(list(rs))7
[‘test‘, ‘str‘, ‘END‘]
reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。
并且reduce()函数还可以传入第三个参数,用来做函数f的初始参数。在Python 3里,reduce()函数已经被从全局名字空间里移除了,它现在被放置在fucntools模块里 用的话要 先引
入:
>>> from functools import reduce
如reduce(f, [1, 3, 5, 7, 9], 100),则先将计算f(100,1)。可以用来做求和,虽然python自带了sum函数。例如:求积:[2, 4, 5, 7, 12]
>>> from functools import reduce>>> num_list = [2, 4, 5, 7, 12]>>> func = lambda x,y : x*y>>> rs = reduce(func,num_list)>>> print(rs)3360
xxxxxxxxxx61
>>> from functools import reduce2
>>> num_list = [2, 4, 5, 7, 12]3
>>> func = lambda x,y : x*y4
>>> rs = reduce(func,num_list)5
>>> print(rs)6
3360
在100的基础上求积:[2, 4, 5, 7, 12]
>>> from functools import reduce>>> num_list = [2, 4, 5, 7, 12]>>> func = lambda x,y : x*y>>> rs = reduce(func,num_list,100)>>> print(rs)336000
xxxxxxxxxx61
>>> from functools import reduce2
>>> num_list = [2, 4, 5, 7, 12]3
>>> func = lambda x,y : x*y4
>>> rs = reduce(func,num_list,100)5
>>> print(rs)6
336000
数学运算函数:? abs(-2) #取绝对值
? round(2.3) #取整
? pow(3,2) #乘方
? cmp(3.1, 3.2) #比较大小
? divmod(9,7) #返回除法结果和余数
? max([2,4,6,8]) #求最大值
? min([1,2, -1, -2]) #求最小值
? sum([-1,1,5,7]) #求和
类型转化函数:? int(“10”) #字符转为整数
? float(4) #转为浮点数
? long(“17”) #转为长整数
? str(3.5) #转为字符串
? complex(2, 5) #返回复数 2 + 5i
? ord(“A”) #A对应的ascii码
? chr(65) #ascii码对应的字符
? unichr(65) #数值65对应的unicode字符
? bool(0) #转换为相应的真假值,0相当于False
btw: “空”值相当于False: [], (), {}, 0, None, 0.0, ‘‘
序列操作函数:? all([True, 2, “wow!"]) #是否所有元素相当于True
? any([0, “”, False, [], None]) #是否有元素相当于True
? sorted([1,7,4]) #序列升序排序
? reversed([1,5,3]) #降序排序
? list((1,2,3)) #转换为表list
? tuple([4,5,4]) #转换为tuple
? dict(a=3,b=“hi”,c=[1,2,3]) #构建字典
其它函数:?id()#查看对象的内存位置
?type()#查看对象类型
?len() #查看对象长度
? input(‘ input something ’) #等待用户输入
? globals() #返回全局变量名,函数名
? locals() #返回局部命名空间
5、面向对象私有属性,所有方法。在方法名,属性名前加“__”。例如: __private_name
__private_name = 1;def __private_func(self,name): print(name);
xxxxxxxxxx31
__private_name = 1;2
def __private_func(self,name):3
print(name);类名称首字母大写:
class ClassName():
xxxxxxxxxx11
class ClassName():
6、模块安装pip:
# 先安装setuptoolshttps://pypi.python.org/pypi/setuptools# 后安装piphttps://pypi.python.org/pypi/pip
xxxxxxxxxx41
# 先安装setuptools2
https://pypi.python.org/pypi/setuptools3
# 后安装pip4
https://pypi.python.org/pypi/pip
# 编译(如果下载的是源码)python setup.py build# 安装(所有python的模块都适用)python setup.py install# 安装模块(安装玩pip后)pip install xxx
xxxxxxxxxx71
# 编译(如果下载的是源码)2
python setup.py build3
# 安装(所有python的模块都适用)4
python setup.py install56
# 安装模块(安装玩pip后)7
pip install xxx引入模块:
import module_name;import module_name as mn;from module_package import module_name;from module_package import *;
xxxxxxxxxx41
import module_name;2
import module_name as mn;3
from module_package import module_name;4
from module_package import *;模块引入路径:
模块搜索路径:1、程序所在的位置2、标准库的安装路径3、操作系统环境变量PYTHONPATH指向的位置但是如果我们的模块不在上述位置时,需要在环境变量中加入如下路径:export PYTHONPATH=$PYTHONPATH:{module_path}
xxxxxxxxxx71
模块搜索路径:2
1、程序所在的位置3
2、标准库的安装路径4
3、操作系统环境变量PYTHONPATH指向的位置56
但是如果我们的模块不在上述位置时,需要在环境变量中加入如下路径:7
export PYTHONPATH=$PYTHONPATH:{module_path}
7、python标准库:? 正则表达式 (re包)
? 时间与日期 (time, datetime包)
? 路径与文件 (os.path包, glob包)
? 文件管理 (部分os包,shutil包)
? 存储对象 (pickle包,cPickle包)
? 子进程 (subprocess包)
? 信号 (signal包)
? 线程同步 (threading包)
? 进程信息 (部分os包)
? 多进程初步 (multiprocessing包)
? 数学 (math包)
? 随机数(random包)
? 循环器 (itertools)
? 数据库 (sqlite3)
? …
? [官方文档]
? Python 2:
? https://docs.python.org/2/library
? Python 3:
? https://docs.python.org/3/library/index.html
python基础
相关内容
- python1.0-----turtle模块,pythonturtle,turtle:绘图模
- python读写本地文件,python文件的读写,当我们需要保存文
- python第二天-字符串操作,python输入字符串,name="my \
- python读写xlsx,python处理excel的优势,1使用openpyx
- python关于type()的用法,typepython,如果按这种形式写ty
- python3中的编码,python3编码,python2字符串
- Python —— sklearn.feature_selection模块,feature,Python ——
- Python3实现短信轰炸机,,短信轰炸机的基本原理
- Python3基础9——range()函数,Pythonrange函数,Python3 ra
- 2、Python函数详解(0601),Hcpl0601,函数和过程的区别:函
评论关闭