iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >我的python学习--第三天
  • 241
分享到

我的python学习--第三天

python 2023-01-31 01:01:12 241人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

第三天  1:列表及Python基础回顾  2:字典 列表字典生成式及应用场景  3:字符串 字典字符串转换及应用场景  4:文件操作 文件字典转换及应用场景  5:总结基础数据结构的知识脑图 -- 增删查改1、列表的操作:  help(l

第三天

  1:列表及Python基础回顾

  2:字典 列表字典生成式及应用场景

  3:字符串 字典字符串转换及应用场景

  4:文件操作 文件字典转换及应用场景

  5:总结基础数据结构的知识脑图 -- 增删查改



1、列表的操作:

  help(list) 列表的帮助,列出所有列表的用法

  type(name) 判断数据类型是列表,元组或字典


  1.1、增

>>> shoplist = ['apple','manGo','carrot','banana']
>>> shoplist.append('rice')                            #方法1  列表尾部追加元素
>>> shoplist.insert(1,'pear')                          #方法2  列表第二个位置插入元素
>>> shoplist
['apple', 'pear', 'mango', 'carrot', 'banana', 'rice']

  1.2、删

>>> del shoplist[0]                                    #方法1  根据索引删除列表中元素
>>> shoplist
['pear', 'mango', 'carrot', 'banana', 'rice']
>>> shoplist.remove('rice')                            #方法2  根据内容删除元素
>>> shoplist
['pear', 'mango', 'carrot', 'banana']
>>> shoplist.pop()                                     #方法3  弹出最后一个元素
'banana'
>>> shoplist
['pear', 'mango', 'carrot']

 1.3、改

>>> shoplist
['pear', 'mango', 'carrot']
>>> shoplist[0] = 'watermelon'                         #通过索引修改
>>> shoplist
['watermelon', 'mango', 'carrot']

 1.4、查

>>> num = [1,2,3,4,5,2]
>>> len(num)                                           #查看列表元素个数
6
>>> max(num)                                           #查看列表中元素最大值
5
>>> min(num)                                           #查看列表中元素最小值
1
>>> num.count(2)                                       #查看列表中某元素个数
2
>>> num.index(3)                                       #根据元素查找索引
2




2、列表的遍历

>>> for i in shoplist:
...     print i
... 
pear
mango
carrot
banana
rice
>>> for i,j in enumerate(shoplist):
...     print i,j
... 
0 pear
1 mango
2 carrot
3 banana
4 rice


3、split()和join(),字符串和列表的转换

>>> ip = '192.168.1.1'
>>> ip.split('.')
['192', '168', '1', '1']
>>> l = ['hello','world','!']
>>> ' '.join(l)
'hello world !'



4、列表生成式

格式:

    [ x for x in 内容] 

    [ x for x in 内容 if 条件] 


    1、把要生成的元素 x 放到前面,执行的时候,先执行后面的for循环

    2、后面跟上for循环,可以有多个for循环,也可以在for循环后面再加个if条件

    3、for循环后面可以是任何方式的迭代器(元组,列表,生成器..),只要可迭代对象的元素中至少有一个值.

>>> [x for x in 'abcd']                                #单循环列表生成式
['a', 'b', 'c', 'd']
>>> l = range(10,15)
>>> l
[10, 11, 12, 13, 14]
>>> [x for x in l if x > 12]                           #带if判断的单循环列表生成式
[13, 14]
>>> [m+n for m in 'abc' for n in 'ABC']                #双循环列表生成式
['aA', 'aB', 'aC', 'bA', 'bB', 'bC', 'cA', 'cB', 'cC'] 
>>> A = ['HELLO','WORLD','APPLE']                      #大小写转换
>>> [x.lower() for x in A]
['hello', 'world', 'apple']
>>> d = {'name':'Alice','age':20,'gender':'F'}         #迭代字典生成列表
>>> field = [k for k in d.keys()]
>>> value = [v for v in d.values()]
>>> field,value
(['gender', 'age', 'name'], ['F', 20, 'Alice'])



5、字典生成式

格式:

    1、在python2.6或更早的版本,字典生成器可以接受迭代的键值对 

      d = dict((k,v) for (k,v) in iterable)

    2、在Python2.7或3以后,可以直接使用字典推导式语法

      d = {k:v for k,v in iterable}

    3、python2.7以上兼容两种写法,python2.6只能使用第一种

    4、可以用任何方式的迭代器(元组,列表,字典...),只要可迭代对象的元素中有两个值

>>> shoplist
['pear', 'mango', 'carrot', 'banana']
>>> dict((k,v) for k,v in enumerate(shoplist))
{0: 'pear', 1: 'mango', 2: 'carrot', 3: 'banana'}
>>> {k:v for k,v in enumerate(shoplist)}
{0: 'pear', 1: 'mango', 2: 'carrot', 3: 'banana'}


1、嵌套元组和嵌套类别可以直接通过dict命令转为字典(嵌套内部的元素只能是2个)

>>> a = [(1,'a'),(2,'b')]
>>> dict(a)
{1: 'a', 2: 'b'}


2、zip()函数可以将多个元组或列表合并,合并规则是每个元组元素个数一致

>>> zip(('name','age'),('Bob',20))
[('name', 'Bob'), ('age', 20)]
>>> zip(['name','age'],['Bob',20])
[('name', 'Bob'), ('age', 20)]
>>> dict(zip(('name','age'),('Bob',20)))
{'age': 20, 'name': 'Bob'}
>>> zip(('name','age'),('Bob',20,'F'))                #元素个数不一致时,以最少的列表为准
[('name', 'Bob'), ('age', 20)]



6、文件操作

  open():

    open('path'): 默认只读打开

    open('path','r+'): 读写打开,如果有内容,就会从头覆盖相应字符串的内容

    open('path','w'): 写入,先删除源文件,重新写入

    open('path','w+'): 读写,同上

    open('path','a'): 写入,在文件末尾追加新内容,文件不存在就先创建

    open('path','a+'): 读写,同上

    open('path','b'): 打开二进制文件,多用于读取图片

    open('path','U'): 支持所有换行符号值\r\n\r\n


  write():write(str)的参数是字符串

  writelines():writelines(sequence)的参数是序列,比如列表,它会帮你迭代写入

  read():每次读取整个文件,试用于小文件

  readline():每次读一行,逐行读取

  readlines():全部读取,自动将文件内容分析成一个行的列表,可以使用for...in...结构进行读取

  close(): 关闭打开的文件





7、格式化

  

  7.1 字符串格式化   

>>> print 'hello,%s'%'world'                                  # 方法1:C格式
hello,world
>>> print 'hello,{}'.fORMat('world')                          # 方法2:C#格式
hello,world
>>> print 'hello,{1}{0}'.format('!','world')                  # 方法3:C#格式
hello,world!


C#格式的优点是可以使用{0},{1},...{n}来匹配对应的参数,如上面的方法3

注:C#格式仅Python2.7以上版本可以使用


  7.2、列表格式化

>>> msg = ['name','Alice']
>>> print '%s:%s'%(msg[0],msg[1])                             # 方法1:C格式
name:Alice
>>> print '%s'%':'.join(msg)                                  # 方法2:C格式(推荐使用)
name:Alice
>>> print '%s%s:%d'%('her ','age',20)                         # 方法3:C格式
>>> print '{} is {}'.format(*msg)                             # 方法4:C#格式
name is Alice
>>> print '{}{}{}'.format('hello ','world ','!')              # 方法5:C#格式
hello world !


注:C#格式仅Python2.7以上版本可以使用


  7.3、字典格式化

>>> d = {'name':'Alice','age':18}
>>> print 'I am %(name)s,my age is %(age)d'%d                  # 方法1
I am Alice,my age is 18
>>> print 'I am {name},my age is {age}'.format(**d)            # 方法2(推荐使用)
I am Alice,my age is 18
>>> print 'I am {name},my age is {age}'.format(name='Alice',age=18) # 方法3
I am Alice,my age is 18



8、字符串处理常用方法:startswith()、endswith和strip()


startswith():判断是否以指定子串开始

endswith():判断是否以指定子串结束

>>> a = 'hello'
>>> a.startswith('a')
False
>>> a.startswith('h')
True
>>> a.startswith('he')
True
>>> a.endswith('o')
True
>>> a.endswith('lo')
True
>>> a.endswith('l')
False


strip():删除字符串开始和结尾处的指定的字符,默认为空格

rstrip():删除字符串结尾处指定的字符

lstrip():删除字符串开始处指定的字符

>>> string = '  aaabb  cc   '
>>> string.strip()
'aaabb  cc'
>>> string.rstrip()
'  aaabb  cc'
>>> string.lstrip()
'aaabb  cc   '
>>> string2 = 'aabbccd'
>>> string2.strip('a')
'bbccd'
>>> string2.strip('d')
'aabbcc'



练习:

  1、将主机ip(192.168.1.1-254)存入列表

hostlist = []
netip = '192.168.1.'
for hostip in range(1,255):
    ip = netip + str(hostip)
    hostlist.append(ip)
print hostlist


 

  2、将这个字典逐个显示{'name':'Alice','Bob':['male',20],'Tom':{'age':25,'gender':'M'}}

d = {'name':'Alice','Bob':['male',20],'Tom':{'age':25,'gender':'M'}}
for k,v in d.items():
    print k+':'
#    if type(v) is list:
    if isinstance(v,list):
        for i in v:
            print i
#    elif type(v) is dict:
    elif isinstance(v,dict):
        for m,n in v.items():
            print m,n
    else:
        print v


 3、将一段文本拼接成num:Word的字典格式

 content="who have touched their lives Love begins with a smile grows with a kiss and ends with a tear The brightest future will always be based on a forgotten past you can not go on well in life until you let go of your past failures and heartaches" 

content="who have touched their lives Love begins with a smile grows with a kiss and ends with a tear The brightest future will always be based on a forgotten past you can not go on well in life until you let go of your past failures and heartaches"

d = {}

for word in content.split():                           #将字符串转化为word:num格式
    if word in d.keys():
        d[word] += 1
    else:
        d[word] = 1
print d

d2 = {}                                                #将k,v互换,为num:list(word)格式
for word,count in d.items():
    d2.setdefault(count,[])
    d2[count].append(word)
print d2


 4、通过文本,构建一个注册,登陆系统


  4.1、注册系统

#!/usr/bin/python
#-coding = utf-8-

fo = open('user.txt','a+')

while True:
    name = raw_input('Please Input your name: ').strip()
    passwd = raw_input('Please Input your password: ').strip()
    repasswd = raw_input('Please Input your password again: ').strip()

    if not name:
        print 'The name can not be null'             #用户名不能为空
        continue
    elif not passwd or passwd!=repasswd:             #密码不能为空,且与再次输入相同
        print 'Wrong password'
        continue
    else:
        print 'login successfully'
        break

fo.write('%s:%s\n'%(name,passwd))                    #写入文件
fo.close()

  

  4.2、登陆系统

#!/usr/bin/python
#-coding=utf-8-

fo = open('user.txt')                                #读取文件
content = fo.readlines()
fo.close()

d = {}
for user in content:
    name = user.strip('\n').split(':')[0]            #获取用户名和密码
    passwd = user.strip('\n').split(':')[1]

    d[name] = passwd
#print d

count = 0
while True:
    count += 1
    if count > 3:
        print 'Sorry,too many error you input,contact the administrator please'
        break                                         #输入出错超过3次,退出
    name = raw_input('Please input your name: ')
    passwd = raw_input('Please input your passwd: ')

    if not name:                                      #对输入的用户名,密码进行判断
        print 'Name can not be null'
        continue
    elif name not in d:
        print 'No such user'
        continue
    elif not passwd or passwd!=d[name]:
        print 'Wrong password'
        continue
    else:
        print 'login successfully'
        break


  5、从一段Nginx访问日志中,获取前十个访问次数最多的ip地址,生成html文件显示

#!/usr/bin/python
#-coding:utf-8-

fo = open('access.log')
content = fo.readlines()
fo.close()

#从字符串转化为列表
l = []
d = {}
for msg in content:
        ipaddr = msg.split(' ')[0]
        l.append(ipaddr)
#print l

#从列表转化为字典
for ipaddr in l:
    if ipaddr in d:
        d[ipaddr] += 1
    else:
        d[ipaddr] = 1

d2 = {}        
for k,v in d.items():
    d2.setdefault(v,[])
    d2[v].append(k)       
#print d2

#找出访问频率最高的前十个ip地址,保存为html格式
count = 0
f = open('access.html','a+')
f.write("<html><table style='border:solid 1px'>")
f.write("<th style='border:solid 1px'>访问次数</th><th style='border:solid 1px'>ip地址</th>")
while count < 10:
    key = max(d2.keys())
    for index in range(len(d2[key])):
        f.write('<tr><td style="border:solid 1px">%s</td><td style="border:solid 1px">%s</td></tr>' % (key,d2[key][index]))
    num = len(d2[key])
    d2.pop(key)
    count = count + num
f.write("</table></html>")
f.close()


html文件效果图:

wKiom1eN3CnArgDsAAARhGZG63c964.png


--结束END--

本文标题: 我的python学习--第三天

本文链接: https://www.lsjlt.com/news/184807.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 我的python学习--第三天
    第三天  1:列表及Python基础回顾  2:字典 列表字典生成式及应用场景  3:字符串 字典字符串转换及应用场景  4:文件操作 文件字典转换及应用场景  5:总结基础数据结构的知识脑图 -- 增删查改1、列表的操作:  help(l...
    99+
    2023-01-31
    python
  • 我的python学习--第十三天
    nginx + uwsgi + flask一、安装1、安装uwsgi[root@yaoliang day_13]# wget http://projects.unbit.it/downloads/uwsgi-2.0.4.tar.gz [ro...
    99+
    2023-01-31
    第十三天 python
  • 我的python学习--第五天
    一、函数的定义:  def 函数名(name,age=20,*params):    函数体    return 返回值  示例:def hello():     print 'hello world'               # pr...
    99+
    2023-01-31
    第五天 python
  • 我的python学习--第四天
    一、首先是对前三天的学习内容进行复习  1、python基础的数据结构      数字(int/float,包括整数和浮点数)          布尔(boolean => True/False)      字符串(str,使用''或...
    99+
    2023-01-31
    第四天 python
  • 我的python学习--第七、八天
    Flask的HTTP方法HTTP(与web应用会话的协议)有许多不同的URL方法。默认情况下,路由只回应GET请求,但是通过route()装饰器传递methods参数可以改变这个行为。HTTP方法告知服务器,客户端想对请求的页面 做些什么。...
    99+
    2023-01-31
    python
  • 我的python学习--第十一天
    上午:作业讲解bootstrap-multiselect插件sweetalert插件下午:datatables----表格插件datetimepicker----时间插件Validform----表单验证插件锁定用户禁止登录---...
    99+
    2023-01-31
    第十一天 python
  • 我的python学习--第十二天(二)
    Python异常处理  Python的异常处理能力是很强大的,可向用户准确反馈出错信息。在Python中,异常也是对象,可对它进行操作。所有异常都是基类Exception的成员,所有异常都从基类Exception继承,而且都在excepti...
    99+
    2023-01-31
    二天 python
  • 我的python学习--第十四天(一)
    一、运维管理系统(基于Flask)回顾1、权限控制  通过session实现权限控制,session是一个全局字典,当用户登录时,可以获取到用户的用户名,通过查找数据库获取用户的权限保存进session中,在每次页面跳转时同过查询sessi...
    99+
    2023-01-31
    第十四天 python
  • 学习python的第三天(变量)
    一.关于python 1.交互式 说一句解释一句 2.命令行式 1.编写文件并且保存 2.打开python解释器,在pyrhon中打开文本,读入内存(python打开的时候,翻译不是瞬间) 3.python解释文本 注意:第二阶段相当于...
    99+
    2023-01-31
    变量 python
  • Python 学习 第三天 课后总结:
    PYTHON学习第三天课后总结: 1,注释:就是对代码起到说明注解的作用。      注释分为单行注释与多行注释。       单行注释:只注释一行代码在需要注释的所在行的行首使用#号来注释此行,注意#与代码之间需要加一个空格    ...
    99+
    2023-01-31
    课后 Python
  • 学习python第二天
    一、python的版本选择与安装后的操作 python 2 vs 3 1。 默认支持中文 2. 不兼容2.x 3. 核心语法调整,更易学 4. 新特性默认只在3.x上有 系统位数 32bit =内存的最大寻址空间是2**32, ...
    99+
    2023-01-31
    第二天 python
  • python 学习第四天
    目录 基本运算符 算术运算符 比较运算符 赋值运算符 逻辑运算符 身份运算符 pyth...
    99+
    2023-01-31
    第四天 python
  • python学习第二天
    目录 操作系统 操作系统干了什么 为什么要有操作系统 操作系统有什么用 应用程序的启动和操作系统的启动 ...
    99+
    2023-01-31
    第二天 python
  • 学习python的第四天(python的
    一.Jupyter的安装以及运行 1.Jupyter的安装 运行CMD,在CMD中输入pip3 --default-timeout=100 install -U jupyter 再输入pip3 install jupyter_contr...
    99+
    2023-01-31
    第四天 python
  • python学习第二天 -----201
    第二周-第02章节-Python3.5-模块初识 #!/usr/bin/env python #-*- coding:utf-8 _*- """ @author:chenjisong @file: sys.py @time: 2019/...
    99+
    2023-01-31
    第二天 python
  • 学习python的第二十天(dateti
    1.datetime模块(用于修改日期) import datetime print(datetime.datetime.now(),type(datetime.datetime.now())) 2019-06-10 19:37:55....
    99+
    2023-01-31
    十天 python dateti
  • Python学习笔记:第一天python
    目录 1. python简介 2. python的安装 3. 编写第一个helloword 4. 变量和常量 5. 数据...
    99+
    2023-01-30
    学习笔记 Python python
  • 学习python的第二十一天(loggi
    1.logging模块 用于程序的运行日志 1.初级 #首先程序运行分会出现5中情况 1.logging.info('info') #程序正常运行级别为10 2.logging.debug('debug') #程序调试...
    99+
    2023-01-31
    python loggi
  • 学习python的第二十一天(hashl
    1.hashlib模块(文件传输中将传输内容用指定算法进行处理) hash是一种算法(Python3.版本里使用hashlib模块代替了md5模块和sha模块,主要提供 SHA1、SHA224、SHA256、SHA384、SHA512、...
    99+
    2023-01-31
    python hashl
  • Python第三天
    python操作文件之读 打开后如何关闭 python操作文件默认动作是读 在打开文件时有时候需要转义 打开文件时文件绝对路径转义方法 相对路径打开文件 非文字类型的文件读操作rb 按行读取 将每一行当成列表的每一个元素 大...
    99+
    2023-01-31
    Python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作