Python 是一种跨平台的计算机程序设计语言,是一种面向对象的动态类型语言,笔记内容包括编译安装python,python列表,字典,元组,文件操作等命令的基本使用技巧。
◆编译安装 Python◆
Python的开发环境安装和配置非常的简单,如果是Linux系统则会默认集成安装了Python环境,Python的可执行文件被放在了/usr/local/bin目录下,库函数被安装在了/usr/local/python 目录中,由于二进制安装非常简单,故此处将使用源码的方式来编译安装Python解释器.
1.首先安装gcc编译器,和编译Python所需要使用的相关依赖包.
[root@localhost ~]# yum -y install gcc zlib zlib-devel openssl openssl-devel libffi-devel wget Package gcc-4.8.5-36.el7.x86_64 already installed and latest version Package zlib-1.2.7-18.el7.x86_64 already installed and latest version Package zlib-devel-1.2.7-18.el7.x86_64 already installed and latest version Package openssl-1.0.2k-16.el7.x86_64 already installed and latest version Package openssl-devel-1.0.2k-16.el7.x86_64 already installed and latest version Package libffi-devel-3.0.13-18.el7.x86_64 already installed and latest version Nothing to do
2.下载Python源代码,然后依次执行nmake命令完成整个编译过程,等待时间较长这里直接略过.
[root@localhost ~]# yum install -y readline [root@localhost ~]# wget https://www.python.org/ftp/python/3.8.0/Python-3.8.0.tgz [root@localhost ~]# tar -xzvf Python-3.8.0.tgz -C /usr/src/ [root@localhost ~]# cd /usr/src/Python-3.8.0/ [root@localhost ~]# ./configure --prefix=/usr/local/python3 [root@localhost ~]# make && make altinstall
3.将Python的头文件拷贝到系统标准目录下,避免直接使用Python时找不到所需的头文件.
[root@localhost ~]# cd /usr/local/python3/include/python3.8 [root@localhost ~]# cp -a ./* /usr/local/include/
4.接着我们备份一下旧版本的Python,并创建符号链接链接到新版本的Python上面.
[root@localhost ~]# cd /usr/bin/ [root@localhost bin]# mv python python.old [root@localhost bin]# ln -s /usr/local/python3/bin/python3.8 /usr/local/bin/python [root@localhost bin]# cp -a /usr/local/python3/bin/python3.8 /usr/bin/python
5.由于YUM仓库是用Python开发,这里为了避免Python2与Python3之间冲突需替换一下.
[root@localhost ~]# vim /usr/bin/yum #!/usr/bin/python2.7 ←此处将python改成python2.7 [root@localhost ~]# vim /usr/libexec/urlgrabber-ext-down #!/usr/bin/python2.7 ←此处将python改成python2.7
6.最后测试Python新版本是否生效,然后再使用YUM命令看是否有效,我这里一切正常.
[root@localhost bin]# python Python 3.8.0 (default, Nov 9 2019, 01:48:59) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> exit()
7.安装pip包管理工具,该工具提供了对Python包的查找、下载、安装、卸载的功能.
[root@localhost ~]# curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py [root@localhost ~]# python get-pip.py [root@localhost ~]# echo "alias pip=\"/usr/local/python3/bin/pip\"" >> /etc/profile [root@localhost ~]# pip --version pip 19.3.1 from /usr/local/python3/lib/python3.8/site-packages/pip (python 3.8)
将Python打包为EXE: 我们安装pyinstaller工具,看能不能打包出独立的可执行文件.
[root@localhost ~]# pip install pyinstaller [root@localhost ~]# pip show pyinstaller [root@localhost ~]# pyinstaller -F ./lyshark.py [root@localhost ~]# pyinstaller -F -w -i lyshark.ico lyshark.py # -w :不提示控制台
将Python编译为EXE: 通过使用Cython可以将Python编译为exe可执行程序,注意是编译并不是打包.
C:/> python -m cython -3 --embed -o lyshark.c lyshark.py C:/> cl /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -I"D:\python\include" /Tc lyshark.c /DWIN32 C:/> link lyshark.obj /SUBSYSTEM:CONSOLE /MACHINE:X64 /LIBPATH:"D:\python\libs" C:/> link lyshark.obj /SUBSYSTEM:WINDOWS /MACHINE:X64 /LIBPATH:"D:\python\libs" /ENTRY:"wmainCRTStartup"
将Python编译为ELF: ELF是Linux系统下的文件运行格式,我们可以Python编译为ELF文件.
[root@localhost ~]# yum install -y epel-release [root@localhost ~]# yum install -y python-pip [root@localhost ~]# yum install -y python-dev* [root@localhost ~]# pip install cython [root@localhost ~]# cython lyshark.py --embed [root@localhost ~]# gcc `python-config --cflags` `python-config --ldflags` lyshark.c -o lyshark
◆Python 输入输出◆
输入与输出是任何一门编程语言中都存在的东西,计算机的本质也就是输入输出,在学习Python之前,必须要先学会输入输出,Python的输入输出非常简单,输入的话直接使用input函数,输出的话就是print函数.
标准输入的用法: 默认接收都视为字符串,如果需要数字则需要另外强制转换为int()转换为数字.
>>> name = input("请输入你的名字:")
请输入你的名字:lyshark
>>> print("Hello " + name)
Hello lyshark
>>> age = input("请输入你的年龄:")
请输入你的年龄:22
>>> type(age)
<class 'str'>
>>> age1 = input("请输入你的年龄:")
>>> age1 = int(age1)  #此处强制类型转换
>>> type(age1)
<class 'int'> 
密码输入专用方法: 输入密码时,需要利用getpass模块中的getpass方法,即:
import getpass
  
# 将用户输入的内容赋值给 pwd 变量
pwd = getpass.getpass("请输入密码:")
请输入密码:
# 打印输入的内容
print(pwd)
简单格式化输出: 通过使用print函数,我们可以实现简单的格式化输出.
>>> string = "hello lyshark"
>>> print(string)
hello lyshark
>>> print(string,) # 不让其自动换行
>>> print('hello', end = " ")
>>>
>>> string = "the length of (%s) is %d"  %("hello lyshark",len("hello lyshark"))
>>> print(string)
the length of (hello lyshark) is 13
>>>
>>> string = "hello {} --> age {}".format("lyshark",22)
>>> print(string)
hello lyshark --> age 22
>>>
>>> string = "i am %(age).2f" %{"age":22}
>>> print(string)
i am 22.00
格式化转换输出: 格式化输出十进制,十六进制,八进制.
>>> import math
>>> nHex=0x20
>>> print("十六进制=%x,十进制=%d,八进制=%o"%(nHex,nHex,nHex))
十六进制=20,十进制=32,八进制=40
>>>
>>> print("PI=%F"%math.pi)
PI=3.141593
>>> print("PI=%10.2f"%math.pi)
PI=      3.14
>>> print("PI=%-10.2f"%math.pi)
PI=3.14
格式化format的详细用法:
>>> print("i am {0}, age {1}, really {0}".format("lyshark",22))
i am lyshark, age 22, really lyshark
>>>
>>> print("i am {name}, age {age}".format(**{"name":"lyshark","age":"22"}))
i am lyshark, age 22
>>>
>>> temp = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
>>> print(temp)
i am 1, age 2, really 3
>>>
>>> temp = "i am {:s}, age {:d}, money {:f}".format("lyshark", 18, 8.1)
>>> print(temp)
i am lyshark, age 18, money 8.100000
>>>
>>> temp = "%r %r %r %r"
>>> print(temp%(1,2,3,4))
1 2 3 4
>>>
>>> print("网站名称:{name},地址:{url}".format(name="myblog",url="www.baidu.com"))
网站名称:myblog,地址:www.baidu.com
>>>
>>> site={"name":"myblog","url":"www.baidu.com"}
>>> print("网站名称:{name} 地址:{url}".format(**site))
网站名称:myblog 地址:www.baidu.com
>>>
>>> my_list = ['myblog','www.baidu.com']
>>> print("网站名称:{0[0]},地址:{0[1]}".format(my_list))
网站名称:myblog,地址:www.baidu.com
◆Python 简单运算◆
运算符用于执行程序代码运算,会针对一个以上操作数项目来进行运算,在Python中运算符大致可以分为7种类型:算术运算符、比较运算符、赋值运算符、逻辑运算符、位运算等,下面的例子将依次介绍这几种运算符的使用技巧.
算数运算符: 用来处理四则运算的符号,所有编程语言都会使用到算术运算符号.
>>> num1 = 10 >>> num2 = 20 >>> >>> num1 + num2 30 >>> num1 - num2 -10 >>> num2 % num1 # 取模:返回除法的余数 0 >>> num2 // num1 # 取整:返回商的整数部分 2 >>> num1 ** num2 # 幂符:返回num1的num2次幂 100000000000000000000
比较运算符: 比较运算符结果是一个逻辑值,不是TRUE(成立)就是FALSE(不成立)的运算符号.
>>> num1 = 10 >>> num2 = 20 >>> >>> num1 == num2 False >>> num1 != num2 True >>> num1 >= num2 False >>> num1 <= num2 True
赋值运算符: 基本的赋值运算符是=(不是等号,等号为==),所以对该运算符往往最后读取.
>>> num1 = 10 >>> num2 = 20 >>> >>> num1 = 10 >>> num1 += 10 20 >>> num1 -= 10 10
位运算符号: 程序中,位运算就是直接对整数在内存中的二进制位进行操作.
>>> a=60                      # 60 = 0011 1100 
>>> b=13                      # 13 = 0000 1101
>>> c=0 
>>>
>>> c= a & b                  # 12 = 0000 1100
>>> print("a与b: ",c)
a与b:  12
>>>
>>> c= a | b                  # 61 = 0011 1101 
>>> print("a或b: ",c)
a或b:  61
>>>
>>> c=a^b                     # 49 = 0011 0001
>>> print("a异或b:",c)
a异或b: 49
>>>
>>> c=a << 2                  # 240 = 1111 0000
>>> print("a左移2",c)
a左移2 240
其他运算符: 其他运算符包括常用的,逻辑运算,成员运算,身份运算等.
>>> num1 = 10 >>> num2 = 20 >>> num3 = 0 >>> list = [10,20,30,40,50] >>> >>> num1 and num3 0 >>> >>> num1 in list # 判断num1是否在list里面 True >>> num1 not in list False >>> >>> num1 is num3 # 判断两个标识符是不是引用自一个对象 True >>> num1 is num2 False >>> num1 is not num2 True
四舍五入: 一些特殊需求情况下使用四舍五入等.
>>> import math >>> >>> math.ceil(3.14) 4 >>> round(3.14) 3
Python 数据类型
数据类型在数据结构中的定义是一个值的集合以及定义在这个值集上的一组操作,在Python当中数据类型包括数值类型、字符类型组、列表、字典、元组、等类型,下面的例子将依次介绍这几种运算符的使用技巧.
◆数值的类型◆
Python支持int、float、bool、complex(复数),在Python中只有一种整数类型int表示为长整型,像大多数语言一样,数值类型的赋值和计算都是很直观的,数值间的数据互换可以参考如下列表:
int(x) #将x转换为一个整数 long(x) #将x转换为一个长整数 float(x) #将x转换到一个浮点数 complex() #创建一个复数 str(x) #将对象x转换为字符串 repr(x) #将对象x转换为表达式字符串 eval(str) #用来计算在字符串中的有效Python表达式,并返回一个对象 tuple(x) #将序列s转换为一个元组 list(x) #将序列s转换为一个列表 chr(x) #将一个整数转换为一个字符 unichr(x) #将一个整数转换为Unicode字符 ord(x) #将一个字符转换为它的整数值 hex(x) #将一个整数转换为一个十六进制字符串 oct(x) #将一个整数转换为一个八进制字符串
整数转其他数值: 使用转换命令将一个整数转换为其他数值.
>>> temp=100 >>> >>> float(temp) 100.0 >>> complex(temp) (100+0j) >>> str(temp) '100'
整数转换字符: 使用转换命令将一个整数转换为字符.
>>> temp=100 >>> >>> chr(temp) 'd' >>> ord(chr(temp)) 100
进制转换: 使用转换命令实现进制转换.
>>> temp=100 >>> >>> hex(temp) '0x64' >>> oct(temp) '0o144'
◆字符串类型◆
所谓字符串就是字符的集合,Python支持字符串这种数据类型,且提供了一些丰富的字符串处理函数,以下列表中就是Python所支持的字符串操作函数,接下来我们将找出几个比较常用的字符串函数来进行演示.
str.capitalize() #将字符串的首字母变大写 str.title() #将字符串中的每个单词的首字母大写 str.upper() #将字符串变成大写 str.lower() #将字符串变成小写 str.index() #找出索引对应的字符串 str.find() #找出索引对应的字符串 str.count() #找出字符串中元素出现的次数 str.format() #也是格式化的一种 str.center() #以什么字符从字符串两边填充 str.join() #以str为分隔符连接字符串 str.split() #以什么为分隔符分隔字符串 str.strip() #将字符串两边中的空格去掉 str.replace() #查找替换 str.isupper() #判断是否为大写 str.islower() #判断是否为小写 str.isalnum() #判断是否是字母数字 str.isalpha() #判断是否是字母下划线 str.isdigit() #判断是否是数字 str.isspace() #判断是否为空 str.startswith() #找出以什么为开头的字符元素 str.endswith() #找出以什么为结尾的字符元素
首字母大写: 使用capitalize()函数,将一个指定字符串首字母变成大写.
>>> str="hello lyshark" >>> >>> str.capitalize() 'Hello lyshark'
全部首字母大写: 使用title()函数,将字符串中的每一个单词的首字母大写.
>>> str="hello lyshark" >>> >>> str.title() 'Hello Lyshark'
查找字符串: 使用index()函数,找出指定字符串的索引编号,不存在则报错.
>>> str="hello lyshark"
>>>
>>> str.index("hello")
0
>>> str.index("lyshark")
6
>>> str.index("mk")
ValueError: substring not found
查找字符串: 使用find()函数,找出指定字符串的索引编号,不存在则返回-1.
>>> str="hello lyshark"
>>>
>>> str.find("hello")
0
>>> str.find("lyshark")
6
>>> str.find("mk")
-1
统计字符串出现次数: 使用count()函数,统计指定字符串的出现次数.
>>> str="hello lyshark"
>>>
>>> str.count("h")
2
>>> str.count("l")
3
>>> str.count("hello")
1
>>> str.count("mk")
0
字符串填充: 使用center()函数,填充指定字符串两边的内容.
>>> str="hello lyshark" >>> >>> str.center(20,'*') '***hello lyshark****' >>> >>> print(str.center(50,'-')) ------------------hello lyshark-------------------
字符串连接: 使用join()函数,将序列中以指定的字符连接生成一个新字符串
>>> str="-"
>>> seq=("hello","lyshark","welcome")
>>>
>>> print(str.join(seq))
hello-lyshark-welcome
>>> list =['1','2','3','4','5']
>>> print(''.join(list))
12345
>>> 'kill %s' % ' '.join(['1024','2234'])
切割字符串: 使用split()函数,指定分割一个字符串,并保存成列表.
>>> str="hello-lyshark-welcome"
>>>
>>> str.split("-")
['hello', 'lyshark', 'welcome']
去除字符串两边空格: 使用strip()函数,去除指定字符串两边空格.
>>> str=" hello lyshark " >>> str ' hello lyshark ' >>> >>> str.strip() 'hello lyshark'
去除字符串(左/右)两边空格: 使用str.lstrip()函数去除字符串左边空格rstrip函数则相反.
>>> str=" hello lyshark " >>> >>> str.rstrip() ' hello lyshark' >>> >>> str.lstrip() 'hello lyshark ' >>>
字符串查找替换: 使用replace()函数,查找并替换指定字符串.
>>> str="hello lyshark"
>>> str
'hello lyshark'
>>>
>>> str.replace("lyshark","mkdirs")
'hello mkdirs'
判断是否为大写: 使用isupper()函数,判断指定字符串是否为大写.
>>> str="LYSHARK" >>> str1="lyshark" >>> >>> str.isupper() True >>> str1.isupper() False
查找开头结尾: 使用startswith()函数,找出指定字母开头的字符元素.
>>> str="hello lyshark welcome"
>>>
>>> str.startswith("hello")
True
>>> str.startswith("lyshark")
False
>>>
>>> str.startswith("lyshark") or str.endswith("welcome")
True
>>> str.startswith("lyshark") and str.endswith("welcome")
False
◆列表的类型◆
列表是Python中最基本的数据结构,同时也是最常用的,列表中的每个元素都分配一个数字-它的位置或索引,第一个索引是0,第二个索引是1,依此类推,,接下来我们将找出几个比较常用的列表操作函数来进行演示.
list.insert() #在列表中指定索引位置前插入元素 list.append() #在列表尾部插入 list.remove() #删除指定的元素 list.pop() #没有指定索引,则弹出最后一个元素,返回的结果是弹出的索引对应的元素 list.copy() #浅复制,只复制第一层,如果有嵌套序列则不会复制,需要复制要导入copy模块 list.extend() #把另外一个列表合并,并不是追加 list.index() #列表中元素出现的索引位置 list.count() #统计列表中元素的次数 list.reverse() #进行逆序 list.sort() #进行排序,无法把数字和字符串一起排序 list1 + list2 #合并两个列表,返回一个新的列表,不会修改原列表 list * N #把list重复N次,返回一个新列表
向列表追加数据: 使用append()函数,追加写入几个数据到指定的列表里.
>>> list = [1,2,3] >>> list [1, 2, 3] >>> >>> list.append(4) >>> list.append(5) >>> list.append(6) >>> >>> list [1, 2, 3, 4, 5, 6]
向列表插入数据: 使用insert()函数,向指定的列表插入几个数据到指定的位置.
>>> list = ["admin","lyshark"] >>> list ['admin', 'lyshark'] >>> >>> list.insert(1,"python") >>> list ['admin', 'python', 'lyshark'] >>> >>> list.insert(2,"ruby") >>> list.insert(2,"ruby") >>> list ['admin', 'python', 'ruby', 'ruby', 'lyshark']
修改指定数据: 使用names[]变量赋值的方式,修改指定元素的字段值.
>>> list ['admin', 'python', 'ruby', 'ruby', 'lyshark'] >>> list[0]="mkdirs" >>> list ['mkdirs', 'python', 'ruby', 'ruby', 'lyshark'] >>> >>> list[3]="pip" >>> list ['mkdirs', 'python', 'ruby', 'pip', 'lyshark']
删除指定数据: 使用remove()函数,删除指定数据,或使用del()函数来删除.
>>> list
['mkdirs', 'python', 'ruby', 'pip', 'lyshark']
>>> 
>>> del list[2]                             #通过下标删除元素
>>> list
['mkdirs', 'python', 'pip', 'lyshark']
>>> 
>>> list.remove("python")                   #删除指定的元素
>>> list
['mkdirs', 'pip', 'lyshark']
>>> 
>>> list.pop()                              #删除列表的最后一个元素
'lyshark'
>>> list.pop()
'pip'
>>> list
['mkdirs']
扩展一个列表: 使用extend()函数,将一个列表追加到另一个列表的后面.
>>> list1 = ["admin","guest","lyshark"] >>> list2 = [1,2,3] >>> >>> list1.extend(list2) >>> list1 ['admin', 'guest', 'lyshark', 1, 2, 3]
浅COPY列表: 使用copy()函数,实现列表的浅Copy.
>>> list1 ['admin', 'guest', 'lyshark', 1, 2, 3] >>> >>> list1_copy = list1.copy() >>> list1_copy ['admin', 'guest', 'lyshark', 1, 2, 3]
统计元素次数: 使用count()函数,统计列表中元素出现的次数.
>>> list = ["admin","admin","lyshark","mkdirs"]
>>>
>>> list.count("admin")
2
>>> list.count("mkdirs")
1
正反向排序: 使用sort(),reverse()函数,给指定列表元素排序.
>>> list = ["admin","python","ruby","1","3","6","9"] >>> list ['admin', 'python', 'ruby', '1', '3', '6', '9'] >>> >>> list.sort() #正向排序,必须元素类型一致 >>> list ['1', '3', '6', '9', 'admin', 'python', 'ruby'] >>> >>> list ['1', '3', '6', '9', 'admin', 'python', 'ruby'] >>> list.reverse() #反向排序,必须元素类型一致 >>> list ['ruby', 'python', 'admin', '9', '6', '3', '1']
获取元素下标: 使用index()函数,来获取元素的下标.
>>> list
['ruby', 'python', 'admin', '9', '6', '3', '1']
>>>
>>> list.index("admin")
2
>>> list.index("1")
6
列表的切片: 使用[]实现列表的各种切片操作.
>>> list=[1,2,3,4,5,6,7,8,9,0] >>> >>> list[1:4] #取出下标1-4的元素,不包括4 [2, 3, 4] >>> >>> list[1:-1] #取出下标1至-1,不包括-1 [2, 3, 4, 5, 6, 7, 8, 9] >>> >>> list[1:] #取出下标从1到最后的数据 [2, 3, 4, 5, 6, 7, 8, 9, 0] >>> >>> list[:] #取出所有元素 [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> >>> list[0::2] #取元素时每次格2格 [1, 3, 5, 7, 9]
通过分片删除数据: 通过使用分片来清除指定列表中的数据.
>>> list [123, 111, 111, 111, 8, 7, 6, 5, 4, 3, 2, 1] >>> list[0:3] [123, 111, 111] >>> >>> list[0:3]=[] #将下标0-3替换成空,不包括3 >>> print(list) [111, 8, 7, 6, 5, 4, 3, 2, 1] >>>
嵌套列表的实现: 一次性声明两个列表,并于数据名称相关联.
>>> list1,list2 = [[1,"a","b"],[2,"a","b"]] >>> >>> print(list1) [1, 'a', 'b'] >>> print(list2) [2, 'a', 'b']
查找元素并修改(1): 查找列表中的指定元素,并修改,只修改第一次发现的.
[root@localhost]# cat test.py
#!/usr/bin/python
name = [1,2,3,4,5,1,5,6]
if 1 in name:
    num_of_ele = name.count(1)
    position_of_ele = name.index(1)
    name[position_of_ele] = 888
    print(name)
[root@localhost]# python test.py 
[888, 2, 3, 4, 5, 1, 5, 6]
查找元素并修改(2): 查找列表中的指定元素,并批量修改,修改所有的.
[root@localhost]# cat test.py
#!/usr/bin/python
name = [1,2,3,4,5,1,5,6]
for i in range(name.count(1)):
    ele_index = name.index(1)
    name[ele_index] = 8888888
print(name)
[root@localhost]# python test.py
[8888888, 2, 3, 4, 5, 8888888, 5, 6]
◆字典的类型◆
字典是另一种可变容器模型,且可存储任意类型对象,字典是使用键值对的数据类型,字典的每个键值(key=>value)用冒号作为分割符,而键值对与键值对之间则用逗号分割,整个字典都被包括在花括号中,且字典还有两个特性,第一个特性字典中的数据是无序存储的,第二个特性字典中的key必须是唯一的,所以Key天生去重,如下是字典的几种格式声明:
person = {"name": "lyshark", "age": 22}
person = dict({"name": "lyshark", "age": 22})
info = {
    'stu1': "加藤鹰",
    'stu2': "波多野结衣",
    'stu3': "小泽玛利亚",
}
字典需要使用字典专有的操作函数,字典的常用函数有以下这几种,后面我会使用不同的例子进行说明.
dict.get(key) #取得某个key的value dict.has_key(key) #判断字典是否有这个key,在python3中已经废除,使用in判断 dict.keys() #返回所有的key为一个列表 dict.values() #返回所有的value为一个列表 dict.items() #将字典的键值拆成元组,全部元组组成一个列表 dict.pop(key) #弹出某个key-value dict.popitem() #随机弹出key-value dict.clear() #清除字典中所有元素 dict.copy() #字典复制,d2=d1.copy()是浅复制,如果深复制需要copy模块 dict.fromkeys(s) #生成一个新字典 dict.update(key) #将一个字典合并到当前字典中 dict.iteritems() #生成key-value迭代器,可以用next()取下个key-value dict.iterkeys() #生成key迭代器 dict.itervalues() #生成values迭代器
增加字典: 在info字典的基础上,增加一个字段info["stu4"] = "苍老师".
>>> info
{'stu1': '加藤鹰', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚'}
>>> info["stu4"] = "苍老师"
>>>
>>> info
{'stu1': '加藤鹰', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚', 'stu4': '苍老师'}
修改字典: 在info字典的基础上,修改将stu1:加藤鹰修改为stu1:金手指.
>>> info
{'stu1': '加藤鹰', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚', 'stu4': '苍老师'}
>>>
>>> info["stu1"] = "金手指"
>>> info
{'stu1': '金手指', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚', 'stu4': '苍老师'}
删除字典: 在info字典的基础上,删除几个字典,以下提供多种删除方法.
>>> info
{'stu1': '金手指', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚', 'stu4': '苍老师'}
>>>
>>> info.pop("stu1")        #通过pop函数删除
'金手指'
>>> info
{'stu2': '波多野结衣', 'stu3': '小泽玛利亚', 'stu4': '苍老师'}
>>>
>>> del info["stu4"]        #通过del命令删除
>>> info
{'stu2': '波多野结衣', 'stu3': '小泽玛利亚'}
>>>
>>> info.popitem()          #随机删除元素
('stu3', '小泽玛利亚')
查找字典: 在info字典基础上,完成几个查询任务,这里提供几种方法.
>>> info
{'stu1': '加藤鹰', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚'}
>>>
>>> "stu1" in info          #标准的查询方式
True
>>>
>>> info.get("stu1")        #使用get函数查询
'加藤鹰'
>>>
>>> info["stu2"]
'波多野结衣'
更新字典: 在info字典的基础上,更新字典内容,将temp字典与info字典合并.
>>> info
{'stu1': '加藤鹰', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚'}
>>>
>>> temp = {1:2,"stu4":"苍老师"}
>>>
>>> info.update(temp)
>>> info
{'stu1': '加藤鹰', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚', 1: 2, 'stu4': '苍老师'}
遍历字典: 这里提供两种字典遍历方法,建议使用第二种,因为其遍历速度最快.
>>> info = {'stu1': '加藤鹰', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚'}
>>>
>>> for keys,values in info.items():
...     print(keys,values)
...
stu1 加藤鹰
stu2 波多野结衣
stu3 小泽玛利亚
>>> for keys in info:
...     print(keys,info[keys])
...
stu1 加藤鹰
stu2 波多野结衣
stu3 小泽玛利亚
索引字典: 字典也支持索引的方式获取字典中的元素,只不过必须以key作为索引.
>>> info = {'stu1': '加藤鹰', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚'}
>>>
>>> info['stu2']
'波多野结衣'
>>>
>>> len(info)
3
>>>
>>> dict = {"姓名":"加藤鹰","得分":[98,99,87]}
>>>
>>> dict["姓名"]
'加藤鹰'
>>> dict["得分"]
[98, 99, 87]
>>> dict["得分"][2:]
[87]
字典解包: 将字典分解为独立的元组并将元组赋值给其他变量.
>>> dict = {"姓名":"加藤鹰","得分":[98,99,87]}
>>> t1,t2 = dict.items()
>>>
>>> print(t1)
('姓名', '加藤鹰')
>>> print(t2)
('得分', [98, 99, 87])
>>>
>>> k1,k2 = {"x":100,"y":200}
>>> print(k1)
x
列表合并为字典: 将两个列表合成一个字典,其中list1是key,list2是values.
>>> dict = {}
>>> list = [100,200,300,400,500]
>>> head = ["MemTotal","MemFree","Cached","SwapTotal","SwapFree"]
>>>
>>> for (keys,values) in zip(head,list):
...     dict[keys] = values
...
>>> dict
{'MemTotal': 100, 'MemFree': 200, 'Cached': 300, 'SwapTotal': 400, 'SwapFree': 500}
>>>
>>> dict(map(lambda x,y:[x,y],head,list))
{'MemTotal': 100, 'MemFree': 200, 'Cached': 300, 'SwapTotal': 400, 'SwapFree': 500}
>>>
>>> dict(zip(head,list))
{'MemTotal': 100, 'MemFree': 200, 'Cached': 300, 'SwapTotal': 400, 'SwapFree': 500}
字典键值对调: 将字典中的键与字典中的值进行位置的对调.
>>> {key:value for key,value in zip(head,list)}
{'MemTotal': 100, 'MemFree': 200, 'Cached': 300, 'SwapTotal': 400, 'SwapFree': 500}
>>> {value:key for key,value in zip(head,list)}
{100: 'MemTotal', 200: 'MemFree', 300: 'Cached', 400: 'SwapTotal', 500: 'SwapFree'}
字典拆分为列表: 将一个完整的字典拆分为两个列表.
>>> dict = {'stu1': '加藤鹰', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚'}
>>> keys= dict.keys()
>>> values = dict.values()
>>>
>>> print("keys:{}".format(keys))
keys:dict_keys(['stu1', 'stu2', 'stu3'])
>>>
>>> dict = {'stu1': '加藤鹰', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚'}
>>>
>>> keys,values = zip(*dict.items())
>>> print("Keys:",str(keys))
Keys: ('stu1', 'stu2', 'stu3')
>>> dict = {'stu1': '加藤鹰', 'stu2': '波多野结衣', 'stu3': '小泽玛利亚'}
>>>
>>> keys = []
>>> values = []
>>> items = dict.items()
>>> for x in items:
...     keys.append(x[0]),values.append(x[1])
...
>>> print(str(keys))
['stu1', 'stu2', 'stu3']
字典合并与拷贝: 合并字典,但是在有相同的key时会覆盖原有的key的值.
>>> dict1 = {"x":1,"y":2}
>>> dict2 = {"a":3,"b":4}
>>> dict3 = {}
>>>
>>> dict3 = {**dict1,**dict2}
>>> print(dict3)
{'x': 1, 'y': 2, 'a': 3, 'b': 4}
>>>
>>> dict3.update(dict1)
>>> dict3.update(dict2)
>>> print(dict3)
{'x': 1, 'y': 2, 'a': 3, 'b': 4}
>>>
>>> import copy
>>> n1 = {"k1": "wu", "k2": 123, "k3": ["lyshark", 456]}
>>> n2 = {}
>>>
>>> n2 = copy.deepcopy(n1)
>>> print(n2)
{'k1': 'wu', 'k2': 123, 'k3': ['lyshark', 456]}
复杂表格数据存储:
>>> dict1 = {"name":"admin","age":19,"salary":3000,"address":"beijing"}
>>> dict2 = {"name":"guest","age":20,"salary":4000,"address":"shanghai"}
>>> dict3 = {"name":"lyshark","age":21,"salary":5000,"address":"shenzhen"}
>>> table = [dict1,dict2,dict3]
# 用于获取指定人的指定字段数据
>>> print(table[1].get("name"))
guest
>>> print(table[2].get("address"))
shenzhen
# 打印表格中所有人的名字
>>> for i in range(len(table)):
...     print(table[i].get("name"))
...
admin
guest
lyshark
◆元组的类型◆
元组是Python中常用的一种数据结构,元组由不同的元素组成,每个元素可以存储不同类型的数据,如字符串、数字甚至元组,元组是"写保护"的,即元组创建后不能再做任何修改操作,元组通常代表一行数据,而元组中的元素代表不同的数据项,元组一旦创建,便不能再修改,所以又叫只读列表,元组使用小括号,列表使用方括号,元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可.
创建元组: 同个几个实例看一下元组是如何被创建的.
>>> tup1 = ("google","baidu",1997,1998)
>>> tup2 = (1,2,3,4,5,6,7)
>>> tup3 = "a","b","c","d"
>>>
>>> tup1
('google', 'baidu', 1997, 1998)
>>> tup2
(1, 2, 3, 4, 5, 6, 7)
>>> tup3
('a', 'b', 'c', 'd')
>>>
>>> type(tup1)
<class 'tuple'>
访问元组: 元组可以使用下标索引来访问元组中的值.
>>> tup1
('google', 'baidu', 1997, 1998)
>>>
>>> print("tup1[0:]",tup1[0])
tup1[0:] google
>>> print("tup1[1:2]",tup1[1:2])
tup1[1:2] ('baidu',)
连接元组: 元组中的元素值是不允许修改的,但我们可以对元组进行连接组合.
>>> tup1 = (1,2,3,4)
>>> tup2 = ("abc","xyz")
>>>
>>> tup3 = tup1+tup2
>>> print(tup3)
(1, 2, 3, 4, 'abc', 'xyz')
删除元组: 元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组.
>>> tup = ("admin","lyshark", 1997, 2000)
>>>
>>> print(tup)
('admin', 'lyshark', 1997, 2000)
>>> del tup;
>>> print(tup)
列表转元组: 将一个列表,强制转换成元祖.
>>> list = ["admin","lyshark","guest"]
>>>
>>> tuple = tuple(list)
>>>
>>> tuple
('admin', 'lyshark', 'guest')
数据统计: 通过使用count(),index()函数统计元组中的其他数据.
>>> tuple
('admin', 'lyshark', 'guest')
>>>
>>> tuple.count("lyshark")    #统计lyshark出现次数
1
>>> tuple.index("lyshark")    #统计lyshark索引位置
1
元素修改(拓展): 在没有嵌套的情况,元组是不可变对象,但是元组内的列表是可变的.
>>> tup=("lyshark",[1,2,3,4,5])
>>> tup
('lyshark', [1, 2, 3, 4, 5])
>>>
>>> tup[1].pop()
5
>>> tup
('lyshark', [1, 2, 3, 4])
元组解包(拓展): 将两个元组,查分开,分别存储在两个变量中.
>>> tup1,tup2=((1,2,3),("a","b","c"))
>>> print(tup1)
(1, 2, 3)
>>>
>>> print(tup2)
('a', 'b', 'c')
◆集合的类型◆
集合是一个无序的,不重复的数据组合,集合天生去重,把一个列表变成集合,就自动去重了,集合不支持:索引、元素获取、切片,且没有特定语法格式,只能通过工厂函数创建set,像字符串则直接创建即可,set集合中的元素必须是可迭代对象,所有元素不会重复,不像list列表是可以重复.
set.add(item) #将item添加到set中,如果item已经在set中,则无任何效果 set.remove(item) #从set中删除item,如果item不是set的成员,则引发KeyError异常 set.discard(item) #从set中删除item.如果item不是set的成员,则无任何效果 set.pop() #随机删除一个集合元素,并从set删除,有变量接收则会接收删除到的元素 set.clear() #删除set中的所有元素 set.copy() #浅复制 set.update(t) #将t中的所有元素添加到set中,t可以是另一个集合、一个序列 set.union(t) #求并集,返回所有在set和t中的元素 set.intersection(t) #求交集,返回所有同时在set和t中的都有的元素 set.intersection_update(t) #计算set与t的交集,并将结果放入set set.difference(t) #求差集,返回所有在set中,但不在t中的元素 set.difference_update(t) #从set中删除同时也在t中的所有元素 set.symmetric_difference(t) #求对称差集,返回所有set中没有t中的元素和t中没有set中的元素组成的集合 set.sysmmetric_difference_update(t) #计算set与t的对称差集,并将结果放入set set.isdisjoint(t) #如果set和t没有相同项,则返回True set.issubset(t) #如果s是t的一个子集,则返回True set.issuperset(t) #如果s是t的一个超集,则返回True
创建集合: 使用两种方式分别创建一个集合元素.
>>> s = {"tom","cat","name","lyshark"}
>>> s = set({"tom","cat","name","lyshark"})
>>>
>>> s
{'tom', 'cat', 'name', 'lyshark'}
>>> type(s)
<class 'set'>
定义可变集合: 定义一个可变集合,集合中的元素不可重复,都是不同的.
>>> set_test = set("hello")
>>> set_test
{'o', 'e', 'l', 'h'}
定义不可变集合: 定义一个不可变集合,集合中的元素不可重复,都是不同的.
>>> set_test = set("hello")
>>> set_test
{'o', 'e', 'l', 'h'}
>>>
>>> no_set_test = frozenset(set_test)
>>> no_set_test
frozenset({'o', 'e', 'l', 'h'})
求子集: 子集为某个集合中一部分的集合,故亦称部分集合.
>>> A = set('abcd')
>>> B = set("cdef")
>>> C = set("ab")
>>>
>>> C<A           #C是A的子集
True
>>> C.issubset(A) #C是A的子集
True
>>> C<B           #C不是B的子集
False
求并集: 一组集合的并集是这些集合的所有元素构成的集合,而不包含其他元素.
>>> A
{'d', 'a', 'c', 'b'}
>>> B
{'f', 'd', 'e', 'c'}
>>>
>>> A | B
{'f', 'b', 'c', 'a', 'e', 'd'}
>>> A.union(B)
{'f', 'b', 'c', 'a', 'e', 'd'}
求交集: 两个集合A和B的交集是含有所有既属于A又属于B的元素,而没有其他元素的集合.
>>> A
{'d', 'a', 'c', 'b'}
>>> B
{'f', 'd', 'e', 'c'}
>>>
>>> A & B
{'c', 'd'}
>>> A.intersection(B)
{'c', 'd'}
求差集: A与B的差集是,所有属于A且不属于B的元素构成的集合.
>>> A
{'d', 'a', 'c', 'b'}
>>> B
{'f', 'd', 'e', 'c'}
>>>
>>> A - B
{'a', 'b'}
>>> A.difference(B)
{'a', 'b'}
对称差: 两个集合的对称差是只属于其中一个集合,而不属于另一个集合的元素组成的集合.
>>> A
{'d', 'a', 'c', 'b'}
>>> B
{'f', 'd', 'e', 'c'}
>>>
>>> A ^ B
{'f', 'b', 'a', 'e'}
>>> A.symmetric_difference(B)
{'f', 'b', 'a', 'e'}
添加元素: 使用add()函数,向一个现有的集合添加一个元素.
>>> s = {1,2,3,4,5,6}
>>> s
{1, 2, 3, 4, 5, 6}
>>> s.add("s")
>>> s.add("e")
>>> s.add("t")
>>>
>>> s
{1, 2, 3, 4, 5, 6, 't', 's', 'e'}
清空集合: 使用clear()函数,清空一个集合中的所有元素.
>>> s
{1, 2, 3, 4, 5, 6, 't', 's', 'e'}
>>>
>>> s.clear()
>>>
>>> s
set()
删除指定元素: 使用remove,discard函数,删除集合中的指定元素.
>>> s = {1,2,3,4,5}
>>> s
{1, 2, 3, 4, 5}
>>>
>>> s.remove(3)
>>> s
{1, 2, 4, 5}
批量更新元素: 使用update()函数,用自己和另一个的并集来更新这个集合.
>>> s ={"p","y"}
>>> s
{'p', 'y'}
>>>
>>> s.update(["H","e"],{"1","2","3"})
>>> s
{'H', '1', 'y', 'p', '2', 'e', '3'}
拓展知识(1): 在多条数据中寻找差异.
# 数据库中原有
old_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 }
}
# cmdb 新汇报的数据
new_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 }
}
old_set=set(old_dict)
new_set=set(new_dict)
 
del_set=old_set.difference(new_set)
add_set=new_set.difference(old_set)
flush_set=old_set.intersection(new_set)
 
for i in del_set:
    old_dict.pop(i)
 
for i in add_set:
    old_dict[i]=new_dict[i]
 
for i in flush_set:
    old_dict[i] = new_dict[i]
print(old_dict)
拓展知识(2): 在多条数据中寻找差异.
# 数据库中原有
old_dict = {
    "#1":8,
    "#2":4,
    "#3":2,
}
# cmdb 新汇报的数据
new_dict = {
    "#1":4,
    "#3":4,
    "#4":2,
}
old_set = set(old_dict.keys())
print(old_set)
new_set = set(new_dict.keys())
print(new_set)
remove_set = old_set.difference(new_set)
print(remove_set)
add_set = new_set.difference(old_set)
print(add_set)
update_set = old_set.intersection(new_set)
print(update_set)
◆序列的补充◆
序列类型表示索引为非负整数的有序对象集合,包括字符串、列表、元组、字符串是字符的,列表和元组是任意python对象的序列,字符和元组属于不可变序列,而列表则支持插入、删除和替换元素等.所有序列都支持迭代,当然元组是不可变对象,对元素的操作是不支持的,当然了有嵌套列表字典是可以操作的,以下是几个常用的序列操作函数:
s + r #连接字符串,与数据 s * n #重复s的n次复制 v1,v2...vn = s #变量解包(unpack) s[i] #索引 s[i:j] #切片 s[i:j:stride] #扩展切片 x in s,x not in s #成员关系 for x in s: #迭代 all(s) #如果s中的所有项都为True,则返回True any(s) #如果s中的任意项为True,则返回True len(s) #长度,元素个数 min(s) #s中的最小项 max(s) #s中的最大项 sum(s [,initial]) #具有可选初始值的项的和
all判断: 如果temp中的所有项都为True,则返回True.
>>> temp = [1,1,1,1,1,1] >>> temp1 = [1,1,1,1,0,1] >>> >>> all(temp) True >>> all(temp1) False
any判断: 如果temp中的任意项为True,则返回True.
>>> temp = [1,1,1,1,1,1] >>> temp1 = [1,1,1,1,0,1] >>> >>> any(temp) True >>> any(temp1) True
len计算元素个数: 计算列表或字典等相关的元素个数.
>>> temp = [1,1,1,1,1,1] >>> len(temp) 6
min返回最小: 返回列表中最小的数值.
>>> temp = [1,2,3,4,5,6,7,8,9] >>> >>> min(temp) 1
max返回最大: 返回列表中最大的数值.
>>> temp = [1,2,3,4,5,6,7,8,9] >>> >>> max(temp) 9
◆文件的操作◆
open: open函数用来打开一个文件,并返回一个句柄.
>>> f=open("./test.txt","r")
>>>
popen: 使用popen存储命令执行结果,并打印执行结果.
>>> temp=os.popen("ifconfig").readlines()
>>> temp
['eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500\n']
read: 此函数一次性读取文件所有内容.
>>> f=open("./test.txt","r")
>>> f.read()
readline: 此函数每次读取一行数据,直到全部读取完毕.
>>> f=open("./test.txt","r")
>>> f.readline()
'root:x:0:0:root:/root:/bin/bash\n'
>>> f.readline()
'bin:x:1:1:bin:/bin:/sbin/nologin\n'
>>> f.readline()
'daemon:x:2:2:daemon:/sbin:/sbin/nologin\n'
readlines: 使用readlines一次性读取全部内容,相当于全部加载.
>>> f=open("./test.txt","r")
>>> f.readlines()
seek: 使用seek移动光标位置,tell获取当前光标位置.
>>> f=open("./test.txt","r")
>>> f.tell()                          #查询当前光标所在位置
0
>>> f.readline()                      #读取一行后
'root:x:0:0:root:/root:/bin/bash\n'
>>> 
>>> f.tell()                          #再次查询光标所在位置
32
>>> 
>>> f.read()                          #完全读取后,光标此时在文件最后面..
'bin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/nologin\n'
>>>
>>> f.seek(32)                        #移动光标到32
>>> 
>>> f.read()                          #重新读取数据
'bin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/nologin\n'
flush: 强制刷新内存中的数据,将其写入磁盘.
>>> import sys
>>> import time
>>> 
>>> for i in range(40):
...     sys.stdout.write("#")
...     sys.stdout.flush()         #强制将内存中的数据写入硬盘
...     time.sleep(0.1)
close: 使用close关闭文件句柄,每次打开文件用完后记得关闭.
>>> f=open("./test.txt","r")
>>> f.readlines()
>>> f.close()
next: 每次读取一行数据,可以使用next函数加载下一行.
>>> f = open("./test.txt", "r")
>>> print ("文件名为: ", f.name)
>>> for index in range(5):
...     line = next(f)
...     print ("第 %d 行 - %s" % (index,line))
>>> f.close()
truncate: 截取数据,可指定每次截取的字节数.
>>> f = open("./test.txt", "r+")
>>> print ("文件名为: ", f.name)
>>> f.truncate(10)           #截取10个字节
>>> str = f.read()
>>> print ("读取数据: %s" % (str))
>>> f.close()
with: 自动打开文件,并在执行完后自动的释放文件句柄.
>>> with open('test.txt') as f:
...     print(f.read())
linecache: 通过使用linecache模块打开一个文件,并计算出文件总行数.
import sys
import linecache
count = len(open("./ip.log","r").readlines())
print("文件行数(包括空格): %d" %count)
count = linecache.getlines("./ip.log")
print("文件行数(支持大文件): %d" %len(count))
Python 流程控制
◆while 循环◆
分支结构:
# -*- coding: utf-8 -*-
import sys
number = 38
user_input = int(input("输入一个数字:"))
if user_input == number:
    print("你猜对了!")
elif user_input < number:
    print("猜小了!")
else:
    print("猜大了!")
实现加法循环:
import sys
count = 1
sum = 0
while count <=100:
    sum+=count
    count+=1
print(sum)
中断循环: 演示一个while循环被中断的情况.
import os
count = 0
while count <=9:
    print(count, end=' ')
    if count == 5:
        break
    count += 1
else:
    print('end')
字符串的打印: 打印指定字符串,循环打印其中的每一个元素,并每次递减.
import sys
string = "hello lyshark"
while string:
    print(string)
    string = string[:-1]
else:
    print("gae over")
列表的打印: 逐一显示指定列表中的所有元素,这里有三种方法.
>>> list=[1,2,3,4,5,6] >>> count =0 >>> >>> while list: ... print(list[0]) ... list.pop(0) ... >>> list=[1,2,3,4,5,6] >>> while list: ... print(list[-1]) ... list.pop() ... >>> list=[1,2,3,4,5,6] >>> while count < len(list): ... print(list[count]) ... count+=1
练习实例: 求100以内所有偶数之和,使用嵌套判断.
>>> num=0 >>> sum=0 >>> while num <=100: ... if num %2 ==0: ... sum=sum+num ... else: ... pass ... num=num+1
练习实例: 逐一显示指定字典的所有键,并于显示结束后说明总键数.
>>> d1 = {'x':1,'y':23,'z':78}
>>> keylists = d1.keys()
>>> while keylists:
        print(keylists[0])
        keylists.pop[0]
    else:
        print(len(d1))
练习实例: 创建一个包含了100以内所有奇数的列表.
>>> l1 = []
>>> x = 1
>>> while x < 100:
        l1.append(x)
        x += 2
练习实例: 如下存在两个列表l1,l2,以第一个列表中的元素为键,以第二个列表中的元素为值生成新字典d1.
>>> l1 = [0,1,2,3,4,5,6]
>>> l2 = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
>>> d1 = {}
>>> count = 0
>>> if len(l1) == len(l2):
    while count < len(l1):
        d1[l1[count]] = l2[count]
        count += 1
>>> print(d1)
练习实例: 循环并打印相关文字,当到达100次的时候退出.
count = 0
while True:
    print("hello lyshark:",count)
    count +=1
    if count == 100:
        print("break")
        break
练习实例: 模拟登陆小程序,程序启动要求输入密码,并判断如果次数小于3次则登陆成功,否则禁止登陆.
import getpass
import os
name = "lyshark"
pwd = "123123"
count = 0
while True:
    if count < 3:
        print("请输入用户名和密码:")
        username = input("用户名:")
        password = getpass.getpass("密码:")
        if username == name and password == pwd:
            print("恭喜你登陆成功!")
            break
        else:
            print("登陆失败!用户名或者密码错误")
    else:
        print("你已经输错3次,正在退出....")
        break
    count += 1
◆for 循环◆
列表遍历: 通过使用for循环打印一个list列表中的元素.
import os
names = ["tom","admin","lyshark","jack"]
for x in names:
    print(x)
列表迭代: 对于一个序列来说,也可以通过索引进行迭代.
import os
names = ["tom","admin","lyshark","jack"]
for x in range(len(names)):
    print(names[x])
打印序列: 通过for循环,遍历并打印一个序列.
import os
T = [(1,2),(3,4),(5,6),(7,8)]
for (a,b) in T:
    print(a,b)
循环遍历: 遍历0-9范围内的所有数字,并通过循环控制语句打印出其中的奇数.
import os
for i in range(10):
    if i % 2 == 0:
        continue
    print(i, end=' ')
循环遍历: 通过循环控制语句打印一个列表中的前3个元素.
import os
names = ['Tom', 'Peter', 'Jerry', 'Jack', 'Lilly']
for i in range(len(names)):
    if i >= 3:
        break
    print(names[i])
循环遍历: 通过for循环打印99乘法表.
import os
for j in range(1, 10):
    for i in range(1, j+1):
        print('%d*%d=%d' % (i, j, i*j), end='\t')
        i += 1
    print()
    j += 1
循环遍历: 通过range函数,我们同样可以实现遍历.
>>> string="hello world my name lyshark"
>>> for i in range(0,len(string),2):
...     print(string[i])
>>> list=[1,2,3,4,5]
>>> for i in range(len(list)):
...     list[i]+=1
>>> list
[2, 3, 4, 5, 6]
>>> for i in range(1,10,2):
    print(i)
enumrate: 给一个可迭代的对象添加序号,默认是编号是从0开始,可以设置从1开始.
>>> list=["苍井空","小泽玛利亚","吉泽明步"]
>>> for (x,y) in enumerate(list,1):
    print(x,y)
1 苍井空
2 小泽玛利亚
3 吉泽明步
zip()函数: zip函数常用于动态的构造字典.
>>> L1 = [1,2,3,4,5]
>>> L2 = ['a','b','c','d','e',]
>>> zip(L1,L2)
>>> 
>>> keys = [1,2,3,4,5,6,7]
>>> vaules = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
>>> D = {}
>>> for (k,v) in zip(keys,values)
       D[k] = v
>>> D
◆其他实例◆
练习实例: 逐一分开显示指定字典d1中的所有元素,也就是字典遍历打印.
>>> d1 = {'x':123,'y':321,'z':734}
>>> for (k,v) in d1.items():
    print(k,v)
    
y 321
x 123
z 734
练习实例: 逐一显示列表中l1中索引为奇数的元素.
>>> l1=['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
>>> 
>>> for i in range(1,len(l1),2):
    print(l1[i])
练习实例: 将属于列表l1,但不属于列表l2的所有元素定义为一个新列表l3,并加入到其中.
>>> l1=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] >>> l2=['Sun','Mon','Tue','Thu','Sat'] >>> l3 = [] >>> for i in l1: >>> if i not in l2: >>> l3.append(i)
练习实例: 请将属于removelist列表中的每个元素从namelist中移除(属于removelist,但不属于namelist的忽略即可).
>>> namelist=['stu1','stu2','stu3','stu4','stu5','stu6','stu7'] >>> removelist=['stu3','stu7','stu9'] >>> for i in removelist: >>> if i in namelist: >>> namelist.remove(i) >>> print(namelist)
练习实例: 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
程序分析:可填在百位、十位、个位的数字都是1、2、3、4,组成所有的排列后再去掉不满足条件的排列.
>>> for i in range(1,5): ... for j in range(1,5): ... for k in range(1,5): ... if(i!=k) and (i!=j) and(j!=k): ... print(i,j,k) ...
练习实例: 输入某年某月某日,程序自动判断这一天是这一年的第几天?
程序分析:以10月1日为例,应该先把前9个月的加起来,然后再加上1天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天.
# -*- coding: UTF-8 -*-
 
year = int(input('year:\n'))
month = int(input('month:\n'))
day = int(input('day:\n'))
 
months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 < month <= 12:
    sum = months[month - 1]
else:
    print ('data error')
sum += day
leap = 0
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
    leap = 1
if (leap == 1) and (month > 2):
    sum += 1
print ('it is the %dth day.' % sum)
练习实例: 输出9*9乘法口诀表,分行与列考虑,共9行9列,i控制行,j控制列.
import os
import sys
for x in range(1,10):
        print()
        for y in range(1,x+1):
                print("%d*%d=%d "%(y,x,x*y),end="")
练习实例: 写一个字符串遍历查找工具,代码如下.
import os
import sys
ls="Type help() for interactive help, or help(object) for help about object"
find="help"
for x in range(len(ls)):
        temp=len(find)
        if str(ls[x:x+temp]) == str(find):
                print(ls[x:x+temp],x)
                break
练习实例: 通过使用time模块中的sleep函数,让程序每隔1秒执行一次循环.
import os
import time
dic={1:"admin",2:"guest"}
for key,value in dict.items(dic):
        print(key,value)
        time.sleep(1)
练习实例: 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数.
import os
import string
strs=input("请输入一个字符串:")
letters=0
space=0
digit=0
others=0
for x in range(len(strs)):
        ch=strs[x]
        if ch.isalpha():
                letters+=1
        elif ch.isspace():
                space+=1
        elif ch.isdigit():
                digit+=1
        else:
                others+=1
print("char=%d,space=%d,digit=%d,others=%d"%(letters,space,digit,others))
练习实例: 读取db配置文件,并按照文件中的账号密码判断是否允许登陆.
import os
import sys
def login(x,y):
    fp=open("db","r",encoding="utf-8")
    data=fp.readline().split(":")
    count=len(open("db","r").readlines())
    username=data[0]
    password=data[1]
    for i in range(3):
        if x==username.strip() and y==password.strip():
            print("登陆成功")
            break
        else:
            data=fp.readline().split(":")
            username=data[0]
            password=data[1]
            continue
    fp.close()
login("admin","admin")
login("lyshark","lyshark")
实现元素分类: 有如下值集合list,将所有大于66的值保存至字典的第一个key中,将小于66的值保存至第二个key的值中,即{'k1': 大于66的所有值,'k2': 小于66的所有值}
list= [11,22,33,44,55,66,77,88,99]
bignum=[]
smallnum=[]
dir={}
for num in list:
    if num>66:
        bignum.append(num)
    if num<66:
        smallnum.append(num)
    else:
        pass
dir['k1']=bignum
dir['k2']=smallnum
print(dir)
实现元素查找: 查找元素,移动空格,并查找以a或A开头,并且以c结尾的所有元素.
li = ["alec", " aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain")
dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
 
for i in li:
    if i.strip().capitalize().startswith('A') and i.strip().endswith('c'):
        print(i)
for i in tu:
    if i.strip().capitalize().startswith('A') and i.strip().endswith('c'):
        print(i)
for i in dic.values():
    if i.strip().capitalize().startswith('A') and i.strip().endswith('c'):
        print (i)
实现商品输出: 输出商品列表,用户输入序号,显示用户选中的商品.
#方法一
l1=[1,2,3,4]
l2=["手机", "电脑", '鼠标垫', '游艇']
d=dict(zip(l1,l2))
print(d)
num=input("请输入商品编号:")
print("你选择的商品为 %s" %d[int(num)])
 
#方法二
li = ["手机", "电脑", '鼠标垫', '游艇']
for k, i in enumerate(li):
    print(k,i)
k=input("请输入商品编号:")
print("你选择的商品为 %s" % li[int(k)])
实现猜数游戏: 实现让用户不断的猜年龄,但只给最多3次机会,再猜不对就退出程序.
# -*- coding:utf-8 -*-
age = 22
count = 0
for i in range(10):
    if count < 3:
        a = int(input("请输入一个猜测的数:"))
        if a == age:
            print("恭喜你,答对了")
            break
        elif a > age:
            print("你猜的数字大了")
        else:
            print("你猜的数字小了")
    else:
        b = input("这都猜不对,你继续玩吗?(yes or not):")
        if b == 'yes':
            count = 0
            continue
        else:
            print("Bye!下次再玩")
    count += 1
实现三级菜单: 实现用户交互,显示省市县三级联动的选择.
dic = {
    "河北": {
        "石家庄": ["鹿泉", "藁城", "元氏"],
        "邯郸": ["永年", "涉县", "磁县"],
    },
    "湖南": {
        "长沙":['a','b','c'],
        "株洲":['d','e','f']
    },
    "湖北": {
        "武汉":['g','h','i'],
        "黄石":['j','k','l']
    }
}
for k in dic.keys():
    print(k)
flag=True
while flag:
    n=input("请输入你所在省:")
    for k in dic.keys():
        if n in dic.keys():
            if k == n:
                for i in dic[n].keys():
                    print(i)
                w = input("请输入你所在的城市:")
                for i in dic[n].keys():
                    if w in dic[n].keys():
                        if i == w:
                            for k in dic[n][w]:
                                print(k)
                            s=input("请输入你所在的县:")
                            for j in dic[n][w]:
                                if s in dic[n][w]:
                                    if j==s:
                                        print("你所在的位置是:%s省%s市%s县" % (n,w,s))
                                        flag = False
                                        break
                                else:
                                    print('不存在,请重新输入')
                                    break
                    else:
                        print('不存在,请重新输入')
                        break
        else:
            print('不存在,请重新输入')
            break
实现一个购物车: 实现一个购物车小程序,并符合以下要求.
product = [
    ("iphone",5800),
    ("watch",380),
    ("bike",800),
    ("book",120),
    ("computer",4000)
]
 
shopping_car = []
 
salary = input("请输入你的金钱: ")
if salary.isdigit():
    salary = int(salary)
    while True:
        for i in enumerate(product):
            print(i)
 
        user_choice = input(">>>或者q:")
 
        if user_choice.isdigit():
            user_choice = int(user_choice)
            if user_choice >= 0 and user_choice < len(product):
                p_item = product[user_choice]
                if salary >= p_item[1]:
                    shopping_car.append(p_item[0])
                    salary -= p_item[1]
                    print("你购买了\033[32m%s\033[0m,你的余额剩余\033[31m%s\033[0m" % (p_item[0], salary))
                else:
                    print("\033[31m你的余额不足\033[0m")
            else:
                print("你输入的项目[%s]不存在,请重新输入" % user_choice)
        elif user_choice == 'q':
            print("你购买了这些商品:".center(30,"-"))
            for i in shopping_car:
                print("\033[32m%s\033[0m" %i)
            print("\033[31m余额%s\033[0m" %salary)
            exit()
        else:
            print("你输入的[%s]不存在" % user_choice)
else:
    print("你输入的金额不正确!请重新输入金额!")
Python 高级特性
◆Python 迭代器◆
迭代器是访问集合元素的一种方式,迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束.迭代器只能往前不会后退,迭代器特别适合用于遍历一些巨大的或是无限的集合,比如遍历大小为GB级别的文件时效率特别高.
创建基本迭代器: 如下首先声明一个列表,然后使用__iter__将其转为迭代器,并通过__next__遍历迭代对象.
>>> list = [1,2,3,4,5,6,7,8,9,10] >>> >>> item = list.__iter__() >>> type(item) <class 'list_iterator'> >>> >>> item.__next__() 1 >>> item.__next__() 2 >>> next(item) 3 >>> next(item) 4
迭代器与元组转换: 通过使用enumerate方法,将列表转为迭代器,然后强制转为元组.
>>> listvar = ["吕洞宾", "张果老", "蓝采和", "特乖离", "和香菇", "汉钟离", "王文"] >>> >>> iter = enumerate(listvar) # 转换为迭代器 >>> dict = tuple(iter) # 转换为元组 >>> print(dict) ((0, '吕洞宾'), (1, '张果老'), (2, '蓝采和'), (3, '特乖离'), (4, '和香菇'), (5, '汉钟离'), (6, '王文'))
循环遍历迭代元素: 由于迭代器遍历结束会报错,所以要使用try语句抛出异常.
>>> listvar = ["吕洞宾", "张果老", "蓝采和", "特乖离", "和香菇", "汉钟离", "王文"] >>> item = listvar.__iter__() >>> >>> while True: ... try: ... temp = next(item) ... print(temp) ... except StopIteration: ... break
◆Python 生成器◆
生成器(Generator)是一个特殊的程序,可以被用作控制循环的迭代行为,Python中生成器是迭代器的一种,使用yield返回值函数,每次调用yield会暂停,而可以使用next()函数和send()函数恢复生成器.
当我们调用一个生成器函数时,其实返回的是一个迭代器对象
在Python语言中,只要表达式中使用了,yield函数,通常将此类函数称为生成器(generator)
运行生成器时,每次遇到yield函数,则会自动保存并暂停执行,直到使用next()方法时,才会继续迭代
跟普通函数不同,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器
在学习生成器之前,需要一些前置知识,先来研究一下列表解析,列表解析是Python迭代机制的一种应用,它常用于实现创建新的列表,因此要放置于[]中,列表解析非常灵活,可以用户快速创建一组相应规则的列表元素,且支持迭代操作.
求阶乘: 通过列表解析式,来实现列表的迭代求阶乘.
>>> temp1 = [1,2,3,4,5] >>> temp2 = [ x ** 2 for x in temp1 ] >>> temp1 [1, 2, 3, 4, 5] >>> temp2 [1, 4, 9, 16, 25]
求阶乘: 通过列表解析式,实现迭代求阶乘,并且只打印大于2(if x>=2)的数据.
>>> temp1 = [1,2,3,4,5] >>> temp2 = [ x**2 for x in temp if x>=2 ] >>> temp1 [1, 2, 3, 4, 5] >>> temp2 [4, 9, 16, 25]
求阶乘: 通过列表解析式,实现迭代求阶乘,并通过range函数生成相关数据.
>>> temp = [ (x**2)/2 for x in range(1,10)] >>> temp [0.5, 2.0, 4.5, 8.0, 12.5, 18.0, 24.5, 32.0, 40.5]
数据合并: 通过列表解析式,实现迭代将两个列表按照规律合并.
>>> temp1=["x","y","z"]
>>> temp2=[1,2,3]
>>> temp3=[ (i,j) for i in temp1 for j in temp2 ]
>>> temp3
[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]
文件过滤: 通过使用列表解析,实现文本的过滤操作.
>>> import os
>>> file_list=os.listdir("/var/log")
>>> file_log=[ i for i in file_list if i.endswith(".log") ]
>>> print(file_log)
['boot.log', 'yum.log', 'ecs_network_optimization.log', 'ntp.log']
>>> file_log=[ i for i in os.listdir("/var/log") if i.endswith(".log") ]
>>> print(file_log)
['boot.log', 'yum.log', 'ecs_network_optimization.log', 'ntp.log']
接下来我们就来研究一下生成器吧,生成器类似于返回值为数组的一个函数,这个函数可以接受参数,可以被调用,但不同于一般的函数会一次性返回包括了所有数值的数组,生成器一次只能产生一个值,这样消耗的内存数量将大大减小,而且允许调用函数可以很快的处理前几个返回值,因此生成器看起来像是一个函数,但是表现得却像是迭代器.
我们先来看以下两种情况的对比,第一种方法很简单,只有把一个列表生成式的[]中括号改为()小括号,就创建了一个生成器.
>>> lis = [x*x for x in range(10)] >>> print(lis) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> generator = (x*x for x in range(10)) >>> print(generator) <generator object <genexpr> at 0x0000022E5C788A98>
如上例子,第一个lis通过列表生成式,创建了一个列表,而第二个generator则打印出一个内存地址,如果我们想获取到第二个变量中的数据,则需要迭代操作,如下所示:
>>> generator = (x*x for x in range(10)) >>> print(next(generator)) 0 >>> print(next(generator)) 1 >>> print(next(generator)) 4 >>> print(next(generator)) 9
以上可以看到,generator保存的是算法,每次调用next(generaotr),就计算出他的下一个元素的值,直到计算出最后一个元素,使用for循环可以简便的遍历出迭代器中的数据,因为generator也是可迭代对象.
>>> generator = (x*x for x in range(10))
>>> 
>>> for i in generator:
    print(i,end="")
0149162536496481
生成器表达式并不真正创建数字列表,而是返回一个生成器对象,此对象在每次计算出一个条目后,把这个条目"产生"(yield)出来,生成器表达式使用了"惰性计算"或称作"延迟求值"的机制序列过长,并且每次只需要获取一个元素时,应当考虑使用生成器表达式而不是列表解析.
>>> import sys >>> >>> yie=( i**2 for i in range(1,10) ) >>> next(yie) 1 >>> next(yie) 4 >>> next(yie) 9 >>> for j in ( i**2 for i in range(1,10)):print(j/2)
练习实例: 通过函数,和yield关键字,生成几个生成器.
>>> import sys
>>> 
>>> def func():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
>>> temp=func()
>>> temp.__next__()
1
>>> temp.__next__()
2
>>> temp.__next__()
3
练习实例: 使用while循环构建一个生成器,并通过for遍历打印出结果.
>>> import sys
>>> 
>>> def yieldNum(x):
    y=0
    while (y <= x):
        yield y
        y += 1
    
>>> yie=yieldNum(5)
>>> for i in yie:
    print(i)
练习实例: 使用生成器求1-10的平方.
>>> def yieldNum():
    x=1
    while (x <=10 ):
        yield x ** 2
        x += 1
>>> yie=yieldNum()
>>> 
>>> for i in yie:
    print(i)
练习实例: 使用生成器,自定义实现range函数.
>>> def xrange(num):
    temp=-1
    while True:
        temp=temp+1
        if (temp >= num):
            return
        else:
            yield temp
>>> xrange(10)
<generator object xrange at 0x038E3030>
练习实例: 通过使用生成器求斐波那契数列.
>>> def fib(max):
    n,a,b=0,0,1
    while n < max:
        yield b
        a,b=b,a+b
        n+=1
    return "done"
>>> f=fib(5)
>>> f
<generator object fib at 0x038F4A20>
练习实例: 使用生成器,在单个进程情况下实现并发效果.
import time
def consumer(name):
    print("%s 准备吃包子啦!" %name)
    while True:
       baozi = yield
 
       print("包子[%s]来了,被[%s]吃了!" %(baozi,name))
 
def producer(name):
    c = consumer('A')
    c2 = consumer('B')
    c.__next__()
    c2.__next__()
    print("老子开始准备做包子啦!")
    for i in range(10):
        time.sleep(1)
        print("做了2个包子!")
        c.send(i)
        c2.send(i)
 
producer("alex")
来源:https://www.cnblogs.com/LyShark/p/12192146.html