码迷,mamicode.com
首页 > 编程语言 > 详细

python世界level2

时间:2019-09-22 14:52:55      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:配置   integer   listen   readline   常用   作用   忘记   三级   beyond   

level2

本级别主要掌握几项基本技能;

  • 列表、元组操作
  • 字符串操作
  • 字典操作
  • 集合操作
  • 文件操作
  • 字符编码与转码

列表与元组操作

  

#!/usr/bin/env python
#Author:Ponke91
names=["zhangyang","lisi","lisi","lisi","lisi","lisi","wangsan"]
names.append("leidongl")
names.insert(1,"lisansan")
print(names)
print(names[1],names[2])
print(names[1:3])#列表切片顾头不顾尾
print(len(names))
print(names[-1])
print(names[-3:-2])
names.pop()#删除
names.sort()#排序,按照AScall码值
names.extend(names)#合并
print(names.index("lisi"))#索引
print(names.count("lisi"))
names.reverse()#反转
names.insert(2,["123","23424"])
#names_old=names.copy()#浅copy,只是copy索引,复制内存地址,只copy第一层并克隆
#如果需要完整copy所有内存数据而不是指针地址,需要import copy 模块
import copy
print(names)
names_old=copy.deepcopy(names)#深copy相当于硬链接
names[2][0]="AAA"
print(names)
print(names_old)
#for i in names_old:
# print(i)
print(names_old[0::2])

 字符串操作

 1 #!/usr/bin/env python
 2 #Author:Ponke91
 3 name="my\t name is {name1},{age}"
 4 print(name.capitalize())#首字母大写
 5 print(name.count("o"))#统计字符串中元素出现得次数
 6 print(name.center(50,"-"))#打印在50个字符得中间位置,其余空白字符用“-”替代
 7 print(name.endswith("91"))#检查字符串得结尾方式
 8 print(name.expandtabs(tabsize=30))
 9 print(name[name.find("name"):9])
10 print(name.format(name1=ponke91,age=99))#格式化
11 print(name.format_map({name1:ponke91,age:99}))#字典格式化
12 print(name.isalnum())#纯阿拉伯数字字母+数字
13 print(name.isalpha())#纯英文字符
14 print(name.isdigit())#整数
15 print(name.isidentifier())#是不是一个合法的变量名
16 print("1".isnumeric())#是不是一个自然数
17 print(name.isspace())#是不是一个空白
18 print(name.istitle())
19 print(name.isprintable())#判断是否可以打印,驱动程序ppy
20 print(name.isupper())#是不是大写
21 print("[‘1‘,2,3]".join([1,2,3]))#将列表作为字符串打印
22 print(name.ljust(50,$))#左边填满
23 print(name.rjust(40,#))#右边填满
24 print(name.lower())#所有字符全部小写
25 print(name.upper())#所有字符全部大写
26 print(name.strip())#去掉所有的空格 回车
27 print(name.lstrip())#左边去掉空格回车
28 print(name.rstrip())#右边去掉空格回车
29 names="ponke91"
30 p=str.maketrans("qwepksr",1234567)
31 print(names.translate(p))
32 print(name.replace(a,A,2))#替换
33 print(name.rfind(a))#从右边寻找
34 print(name.split())#将字符串分割成列表
35 print(name.splitlines())#将字符串按照换行来区分
36 print(name.swapcase())#反转字符大小写
37 print(name.title())#首字母大写
38 print(name.zfill(50))#用0填充

字典操作

 1 #!/usr/bin/env python
 2 #Author:Ponke91
 3 ‘‘‘消防救援衔高的人员对消防救援衔低的人员,消防救援衔高的为上级。当消防救援衔高的人员隶属于消防救援衔低的人员时,担任领导职务的或者领导职务高的为上级。消防救援衔按照管理指挥干部、专业技术干部和消防员分别设置。
 4 管理指挥干部消防救援衔设下列三等十一级:
 5   (一)总监、副总监、助理总监;
 6   (二)指挥长:高级指挥长、一级指挥长、二级指挥长、三级指挥长;
 7   (三)指挥员:一级指挥员、二级指挥员、三级指挥员、四级指挥员。
 8   专业技术干部消防救援衔设下列两等八级,在消防救援衔前冠以“专业技术”:
 9   (一)指挥长:高级指挥长、一级指挥长、二级指挥长、三级指挥长;
10   (二)指挥员:一级指挥员、二级指挥员、三级指挥员、四级指挥员。
11   消防员消防救援衔设下列三等八级:
12   (一)高级消防员:一级消防长、二级消防长、三级消防长;
13   (二)中级消防员:一级消防士、一级消防士;
14   (三)初级消防员:三级消防士、四级消防士、预备消防士。‘‘‘
15 Commander={
16     管理指挥干部:{
17     总监:[总监, 副总监, 助理总监],
18     指挥长:[高级指挥长, 一级指挥长, 二级指挥长, 三级指挥长],
19     指挥员:[一级指挥员, 二级指挥员, 三级指挥员, 四级指挥员]},
20     专业技术干部:{
21     指挥长:[高级指挥长,一级指挥长,二级指挥长,三级指挥长],
22     指挥员:[一级指挥员,二级指挥员,三级指挥员,四级指挥员]},
23     消防员:{
24     消防长:[一级消防长, 二级消防长, 三级消防长],
25     消防士:[一级消防士, 二级消防士],
26     消防士2:[三级消防士, 四级消防士, 预备消防士]}}
27 flag=False
28 while not flag:
29     for i in Commander:
30         print(i)
31     choice=input("选择进入第一层:")
32     if choice in Commander:
33         while not flag:
34             for n in Commander[choice]:
35                 print(\t,n)
36             choice2=input("选择进入第二层:")
37             if choice2 in Commander[choice]:
38                 while not flag:
39                     for s in Commander[choice][choice2]:
40                         print(s)
41                     choice3=input("选择进入第三层:")
42                     if choice3==b:
43                         break
44                     elif choice3==q:
45                         flag=True
46             if choice2==b:
47                 break
48             elif choice2== q:
49                 flag = True
50     if choice == b:
51         break
52     elif choice == q:
53         flag = True
 1 #!/usr/bin/env python
 2 #Author:Ponke91
 3 xiaozi={
 4     stu001:001,
 5     stu002:003,
 6     stu004:3,
 7     stu005:[1,2]
 8 
 9 }
10 print(xiaozi[stu005])
11 xiaozi[stu002]=奥迪
12 
13 del xiaozi[stu001]
14 xiaozi.pop("stu004")#删除
15 #xiaozi.popitem()#随机删除
16 print(xiaozi)
17 print(xiaozi.get("stu005"))
18 print("stu006" in xiaozi)
19 xiaozi.values()#所有的值
20 xiaozi.setdefault("台湾",{www.baidu.com:[1,2]})#使用方式在字典中查找是否存在该值,如果存在不修改直接返回该值,如果不存在则修改
21 xxx={zhangsan:lsi,afjals:111}
22 xiaozi.update(xxx)#合并两个列表,重复的值使用XXX更新,没有的值进行创建
23 xiaozi.items()
24 print(xiaozi.items())#字典转换成列表
25 t=dict.fromkeys([1,2,3],oooo)#初始化一个字典 内存地址不可变
26 print(t)

元组

1 #!/usr/bin/env python
2 #Author:Ponke91
3 
4 Tuple=("ponke",dd,33141)#元组不可变只有 ,常用来作为重要参数不可变
5 print(Tuple.count("ponke"))#count 统计
6 print(Tuple.index(dd))#,index 获取下标

参考网址 https://www.cnblogs.com/alex3714/articles/5717620.html

集合操作

  

集合是一个无序的,不重复的数据组合,它的主要作用如下:

  • 去重,把一个列表变成集合,就自动去重了
  • 关系测试,测试两组数据之前的交集、差集、并集等关系

常用操作

s = set([3,5,9,10])      #创建一个数值集合  
  
t = set("Hello")         #创建一个唯一字符的集合  


a = t | s          # t 和 s的并集  
  
b = t & s          # t 和 s的交集  
  
c = t – s          # 求差集(项在t中,但不在s中)  
  
d = t ^ s          # 对称差集(项在t或s中,但不会同时出现在二者中)  
  
   
  
基本操作:  
  
t.add(x)            # 添加一项  
  
s.update([10,37,42])  # 在s中添加多项  
  
   
  
使用remove()可以删除一项:  
  
t.remove(H)  
  
  
len(s)  
set 的长度  
  
x in s  
测试 x 是否是 s 的成员  
  
x not in s  
测试 x 是否不是 s 的成员  
  
s.issubset(t)  
s <= t  
测试是否 s 中的每一个元素都在 t 中  
  
s.issuperset(t)  
s >= t  
测试是否 t 中的每一个元素都在 s 中  
  
s.union(t)  
s | t  
返回一个新的 set 包含 s 和 t 中的每一个元素  
  
s.intersection(t)  
s & t  
返回一个新的 set 包含 s 和 t 中的公共元素  
  
s.difference(t)  
s - t  
返回一个新的 set 包含 s 中有但是 t 中没有的元素  
  
s.symmetric_difference(t)  
s ^ t  
返回一个新的 set 包含 s 和 t 中不重复的元素  
  
s.copy()  
返回 set “s”的一个浅复制

5文件操作

对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件 

现有文件如下

Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戏弄生命 视其为愚蠢的游戏
The way the evening breeze
就如夜晚的微风
May tease the candle flame
逗弄蜡烛的火苗
The thousand dreams I dreamed
我曾千万次梦见
The splendid things I planned
那些我计划的绚丽蓝图
I always built to last on weak and shifting sand
但我总是将之建筑在易逝的流沙上
I lived by night and shunned the naked light of day
我夜夜笙歌 逃避白昼赤裸的阳光
And only now I see how the time ran away
事到如今我才看清岁月是如何匆匆流逝
Yesterday when I was young
昨日当我年少轻狂
So many lovely songs were waiting to be sung
有那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
I ran so fast that time and youth at last ran out
我飞快地奔走 最终时光与青春消逝殆尽
I never stopped to think what life was all about
我从未停下脚步去思考生命的意义
And every conversation that I can now recall
如今回想起的所有对话
Concerned itself with me and nothing else at all
除了和我相关的 什么都记不得了
The game of love I played with arrogance and pride
我用自负和傲慢玩着爱情的游戏
And every flame I lit too quickly, quickly died
所有我点燃的火焰都熄灭得太快
The friends I made all somehow seemed to slip away
所有我交的朋友似乎都不知不觉地离开了
And only now Im left alone to end the play, yeah
只剩我一个人在台上来结束这场闹剧
Oh, yesterday when I was young
噢 昨日当我年少轻狂
So many, many songs were waiting to be sung
有那么那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
There are so many songs in me that wont be sung
我有太多歌曲永远不会被唱起
I feel the bitter taste of tears upon my tongue
我尝到了舌尖泪水的苦涩滋味
The time has come for me to pay for yesterday
终于到了付出代价的时间 为了昨日
When I was young
当我年少轻狂

文件操作

  

f = open(lyrics) #打开文件
first_line = f.readline()
print(first line:,first_line) #读一行
print(我是分隔线.center(50,-))
data = f.read()# 读取剩下的所有内容,文件大时不要用
print(data) #打印文件
 
f.close() #关闭文件

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab
 1 def close(self): # real signature unknown; restored from __doc__
 2         """
 3         Close the file.
 4         
 5         A closed file cannot be used for further I/O operations.  close() may be
 6         called more than once without error.
 7         """
 8         pass
 9 
10     def fileno(self, *args, **kwargs): # real signature unknown
11         """ Return the underlying file descriptor (an integer). """
12         pass
13 
14     def isatty(self, *args, **kwargs): # real signature unknown
15         """ True if the file is connected to a TTY device. """
16         pass
17 
18     def read(self, size=-1): # known case of _io.FileIO.read
19         """
20         注意,不一定能全读回来
21         Read at most size bytes, returned as bytes.
22         
23         Only makes one system call, so less data may be returned than requested.
24         In non-blocking mode, returns None if no data is available.
25         Return an empty bytes object at EOF.
26         """
27         return ""
28 
29     def readable(self, *args, **kwargs): # real signature unknown
30         """ True if file was opened in a read mode. """
31         pass
32 
33     def readall(self, *args, **kwargs): # real signature unknown
34         """
35         Read all data from the file, returned as bytes.
36         
37         In non-blocking mode, returns as much as is immediately available,
38         or None if no data is available.  Return an empty bytes object at EOF.
39         """
40         pass
41 
42     def readinto(self): # real signature unknown; restored from __doc__
43         """ Same as RawIOBase.readinto(). """
44         pass #不要用,没人知道它是干嘛用的
45 
46     def seek(self, *args, **kwargs): # real signature unknown
47         """
48         Move to new file position and return the file position.
49         
50         Argument offset is a byte count.  Optional argument whence defaults to
51         SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
52         are SEEK_CUR or 1 (move relative to current position, positive or negative),
53         and SEEK_END or 2 (move relative to end of file, usually negative, although
54         many platforms allow seeking beyond the end of a file).
55         
56         Note that not all file objects are seekable.
57         """
58         pass
59 
60     def seekable(self, *args, **kwargs): # real signature unknown
61         """ True if file supports random-access. """
62         pass
63 
64     def tell(self, *args, **kwargs): # real signature unknown
65         """
66         Current file position.
67         
68         Can raise OSError for non seekable files.
69         """
70         pass
71 
72     def truncate(self, *args, **kwargs): # real signature unknown
73         """
74         Truncate the file to at most size bytes and return the truncated size.
75         
76         Size defaults to the current file position, as returned by tell().
77         The current file position is changed to the value of size.
78         """
79         pass
80 
81     def writable(self, *args, **kwargs): # real signature unknown
82         """ True if file was opened in a write mode. """
83         pass
84 
85     def write(self, *args, **kwargs): # real signature unknown
86         """
87         Write bytes b to file, return number written.
88         
89         Only makes one system call, so not all of the data may be written.
90         The number of bytes actually written is returned.  In non-blocking mode,
91         returns None if the write would block.
92         """
93         pass

with 语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open(log,r) as f:
     
    ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即

1 with open(log1) as obj1, open(log2) as obj2:
2     pass
技术图片
 1 1、查
 2     输入:www.oldboy.org
 3     获取当前backend下的所有记录
 4 
 5 2、新建
 6     输入:
 7         arg = {
 8             bakend: www.oldboy.org,
 9             record:{
10                 server: 100.1.7.9,
11                 weight: 20,
12                 maxconn: 30
13             }
14         }
15 
16 3、删除
17     输入:
18         arg = {
19             bakend: www.oldboy.org,
20             record:{
21                 server: 100.1.7.9,
22                 weight: 20,
23                 maxconn: 30
24             }
25         }
26 
27 需求
View Code
技术图片
 1 global       
 2         log 127.0.0.1 local2
 3         daemon
 4         maxconn 256
 5         log 127.0.0.1 local2 info
 6 defaults
 7         log global
 8         mode http
 9         timeout connect 5000ms
10         timeout client 50000ms
11         timeout server 50000ms
12         option  dontlognull
13 
14 listen stats :8888
15         stats enable
16         stats uri       /admin
17         stats auth      admin:1234
18 
19 frontend oldboy.org
20         bind 0.0.0.0:80
21         option httplog
22         option httpclose
23         option  forwardfor
24         log global
25         acl www hdr_reg(host) -i www.oldboy.org
26         use_backend www.oldboy.org if www
27 
28 backend www.oldboy.org
29         server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
30 
31 原配置文件
View Code

 

python世界level2

标签:配置   integer   listen   readline   常用   作用   忘记   三级   beyond   

原文地址:https://www.cnblogs.com/ponke91/p/11567343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!