【Python第二篇】Python基础之列表、字典、集合、函数

本节内容

  1. 列表、元组操作
  2. 字符串操作
  3. 字典操作
  4. 集合操作
  5. 函数
  6. 三元运算
  7. lambda表达式
  8. 内置函数(文件操作)
  9. 函数递归

1. 列表、元组操作

列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作

定义列表

1
names = ['Alex',"Tenglan",'Eric']

通过下标访问列表中的元素,下标从0开始计数

1
2
3
4
5
6
7
8
>>> names[0]
'Alex'
>>> names[2]
'Eric'
>>> names[-1]
'Eric'
>>> names[-2#还可以倒着取
'Tenglan'

 切片:取多个元素

>>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
>>> names[1:4]  #取下标1至下标4之间的数字,包括1,不包括4
['Tenglan', 'Eric', 'Rain']
>>> names[1:-1] #取下标1至-1的值,不包括-1
['Tenglan', 'Eric', 'Rain', 'Tom']
>>> names[0:3] 
['Alex', 'Tenglan', 'Eric']
>>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样
['Alex', 'Tenglan', 'Eric']
>>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写
['Rain', 'Tom', 'Amy'] 
>>> names[3:-1] #这样-1就不会被包含了
['Rain', 'Tom']
>>> names[0::2] #后面的2是代表,每隔一个元素,就取一个
['Alex', 'Eric', 'Tom'] 
>>> names[::2] #和上句效果一样
['Alex', 'Eric', 'Tom']
View Code

追加

>>> names
['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy']
>>> names.append("我是新来的")
>>> names
['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
View Code

插入

>>> names
['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
>>> names.insert(2,"强行从Eric前面插入")
>>> names
['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']

>>> names.insert(5,"从eric后面插入试试新姿势")
>>> names
['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
View Code

修改

>>> names
['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
>>> names[2] = "该换人了"
>>> names
['Alex', 'Tenglan', '该换人了', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
View Code

删除

>>> del names[2] 
>>> names
['Alex', 'Tenglan', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
>>> del names[4]
>>> names
['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
>>> 
>>> names.remove("Eric") #删除指定元素
>>> names
['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', '我是新来的']
>>> names.pop() #删除列表最后一个值 
'我是新来的'
>>> names
['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
View Code

扩展

>>> names
['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
>>> b = [1,2,3]
>>> names.extend(b)
>>> names
['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
View Code

统计

>>> names
['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3]
>>> names.count("Amy")
2
View Code

排序&翻转

>>> names
['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3]
>>> names.sort() #排序
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()   #3.0里不同数据类型不能放在一起排序了,擦
>>> names[-3] = '1'
>>> names[-2] = '2'
>>> names[-1] = '3'
>>> names
['Alex', 'Amy', 'Amy', 'Tenglan', 'Tom', '1', '2', '3']
>>> names.sort()
>>> names
['1', '2', '3', 'Alex', 'Amy', 'Amy', 'Tenglan', 'Tom']

>>> names.reverse() #反转
>>> names
['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']
View Code

获取下标

>>> names
['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']
>>> names.index("Amy")
2 #只返回找到的第一个下标
View Code

元组

元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表

语法

1
names = ("alex","jack","eric")

它只有2个方法,一个是count,一个是index。

程序练习 

请写出以下程序。

程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额

程序代码如下:

salary = input('input your salary:')
if salary.isdigit():
    salary =int(salary)
else:
    exit('Invalid data type')

welcome_msg = 'Welcome to WuMei shopping mall'.center(50,'-')
print(welcome_msg)

exit_flag = False
product_list = [
    ('Iphone',5888),
    ('Mac Air',8000),
    ('Mac Pro',9000),
    ('XiaoMi2',19.9),
    ('Coffee',30),
    ('Tesla',820000),
    ('Bike',700),
    ('Cloth', 200),]

shop_cat = []
while exit_flag is not True:
    print('product list'.center(50,'-'))
    for name in enumerate(product_list): #枚举元组
        index = name[0]
        p_name = name[1][0]
        p_price = name[1][1]
        print(index,'.',p_name,p_price)

    user_choice = input("[q=quit,c=check]What do you want to buy?:")
    if user_choice.isdigit():
         user_choice = int(user_choice)
         if user_choice < len(product_list):
             p_item = product_list[user_choice]
             if p_item[1] <= salary:
                shop_cat.append(p_item)
                salary -= p_item[1]
                print("Add [%s] into shop car ,you blance is \033[31;1m[%s]\033[0m" %(p_item,salary))
             else:
                 print('Your blance is [%s],cannot afford this.'% salary)
         else:
             print('\033[31;1m Invalid option,please select 0-%d\033[0m' %(len(product_list)-1) )
    else:
         if user_choice == 'q' or user_choice =='quit':
             print("purchased products as blow".center(40,'-'))
             for name in shop_cat:
                 print(name)
             print('END'.center(40,'-'))
             print('Your balance is [%s]'%salary)
             print('bye')
             exit_flag = True
         elif user_choice == 'c' or user_choice =='check':
             print("purchased products as blow".center(40,'-'))
             for name in shop_cat:
                 print(name)
             print('END'.center(40,'-'))
             print('Your balance is \033[31;1m[%s]\033[0m'% salary)
View Code

2. 字符串操作

name = "chris,jack,rain"
print(name.split(","))
print("|".join(name))

username = input('your name:')
if username.strip() == 'fuyf':
    print('weblcome')

name = 'fu ye feng'
print(name.center(40,'-'))
print('' in name)
print(name.capitalize())

msg = "hello,{name},it's been a long {age} no see"
print(msg.format(name='fuyf',age=22))
msg2 = "hahah{0},dddd{1}"
print(msg2.format('chris',22))

age = input('your age:')
if age.isdigit():
    age = int(age)
else:
    print("invalid data type")

name = 'fuyf123'
print(name.endswith('f'))
print(name.startswith('3'))
print(name.upper().lower())


format :
    >>> msg = "my name is {}, and age is {}"
    >>> msg.format("alex",22)
    'my name is alex, and age is 22'
    >>> msg = "my name is {1}, and age is {0}"
    >>> msg.format("alex",22)
    'my name is 22, and age is alex'
    >>> msg = "my name is {name}, and age is {age}"
    >>> msg.format(age=22,name="ale")
    'my name is ale, and age is 22'
format_map
    >>> msg.format_map({'name':'alex','age':22})
    'my name is alex, and age is 22'
View Code

3. 字典操作

字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

语法:

info = {
    'stu1101': "TengLan Wu",
    'stu1102': "LongZe Luola",
    'stu1103': "XiaoZe Maliya",
}

字典的特性:

  • dict是无序的
  • key必须是唯一的,so 天生去重

字典常用操作:

增加
>>> info["stu1104"] = "苍井空"
>>> info
{'stu1102': 'LongZe Luola', 'stu1104': '苍井空', 'stu1103': 'XiaoZe Maliya', 'stu1101': 'TengLan Wu'}

修改
>>> info['stu1101'] = "武藤兰"
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'}

删除
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'}
>>> info.pop("stu1101") #标准删除姿势
'武藤兰'
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
>>> del info['stu1103'] #换个姿势删除
>>> info
{'stu1102': 'LongZe Luola'}
>>> 
>>> 
>>> 
>>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} #随机删除
>>> info.popitem()
('stu1102', 'LongZe Luola')
>>> info
{'stu1103': 'XiaoZe Maliya'}

查找
>>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
>>> 
>>> "stu1102" in info #标准用法
True
>>> info.get("stu1102")  #获取
'LongZe Luola'
>>> info["stu1102"] #同上,但是看下面
'LongZe Luola'
>>> info["stu1105"]  #如果一个key不存在,就报错,get不会,不存在只返回None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'stu1105'

多级字典嵌套及操作
av_catalog = {
    "欧美":{
        "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
        "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
        "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
        "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
    },
    "日韩":{
        "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
    },
    "大陆":{
        "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
    }
}

av_catalog["大陆"]["1024"][1] += ",可以用爬虫爬下来"
print(av_catalog["大陆"]["1024"])
#ouput 
['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']

其它姿势
#values
>>> info.values()
dict_values(['LongZe Luola', 'XiaoZe Maliya'])

#keys
>>> info.keys()
dict_keys(['stu1102', 'stu1103'])


#setdefault
>>> info.setdefault("stu1106","Alex")
'Alex'
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
>>> info.setdefault("stu1102","龙泽萝拉")
'LongZe Luola'
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}


#update 
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
>>> b = {1:2,3:4, "stu1102":"龙泽萝拉"}
>>> info.update(b)
>>> info
{'stu1102': '龙泽萝拉', 1: 2, 3: 4, 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}

#items
info.items()
dict_items([('stu1102', '龙泽萝拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')])


#通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个
>>> dict.fromkeys([1,2,3],'testd')
{1: 'testd', 2: 'testd', 3: 'testd'}
View Code

循环dict 

#方法1
for key in info:
print(key,info[key])

#方法2
for k,v in info.items(): #会先把dict转成list,数据里大时莫用
print(k,v)

程序练习

程序: 三级菜单

要求: 

  1. 打印省、市、县三级菜单
  2. 可返回上一级
  3. 可随时退出程序
menu = {
    '湖南':{
            '长沙':[
                '望城县',
                '刘阳市',
                '开元区',
            ],
            '株洲': [
                '荷塘区',
                '醴陵市',
                '攸县',
            ]
    },
    '浙江':{
            '杭州':[
                '滨江区',
                '西湖区',
                '江干区',
            ]
        }
}

exit_flag = False
current_layer = menu

layers = [menu]

while not  exit_flag:
    for k in current_layer:
        print(k)
    choice = input("选择菜单>>:").strip()
    if choice == "b" or choice =='back': #返回上一级菜单
        current_layer = layers[-1]
        layers.pop()
    elif choice not  in current_layer:
        print('\033[31;1myour select menu invalid,please select again:\033[0m')
        continue
    else:
        layers.append(current_layer)
        current_layer = current_layer[choice]

4.集合操作

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

  • 去重,把一个列表变成集合,就自动去重了
  • 关系测试,测试两组数据之前的交集、差集、并集等关系
#创建集合
s = set([3, 5, 9, 3,10])
s1 = {1,'ff'}
s2 = set("Hello")

s1 = {1,2,3}
s2 = {2,3,4}

s1.add(44)  #加入一条数据
print(s1)
s1.clear() #清空数据
s3 = s1.difference(s2) #s1中有,s2没有的

s3 = s1.symmetric_difference(s2) #s1中有,s2没有的和s2中有,s1没有的
s1.difference_update(s2) #s1中有的,s2中没有的更新为s1

s1.symmetric_difference_update(s2)

s1.discard(2)   #删除某个元素

s2.remove(2)  #删除某个元素,不存在则报错

s2.pop() #随机移除

ret = s2.pop() #记录随机删除的数
print(ret)

s3=s1.intersection(s2) #取交集

s1.intersection_update(s2)  #交集更新到s1
s1.issubset(s2)  #子集
s1.issuperset(s2) #超集
s3 = s1.union(s2)  #并集

li = [11,22,33]
s1.update(li)  #加入多条数据,可以是列表、元组、字符串等可以迭代的对象
print(s1)

5.函数

函数式编程最重要的是增强代码的重用性和可读性

定义: 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可

特性:

  1. 减少重复代码
  2. 使程序变的可扩展
  3. 使程序变得易维护

语法定义:

def 函数名(参数):   

    ...
    函数体
    ...
    返回值
 

函数有三种不同的参数:

  • 普通参数
  • 默认参数   注:默认参数需要放在参数列表最后
  • 动态参数
举例:
def send(t1,t2,t3='ok'):  #t3为默认参数
    print(t1,t2,t3)
    return True

send('alex','fuyf','ok1') #普通参数
send(t2='alex',t1='fuyf')  #指定参数
============================================================
动态参数:
def f1(name,age,*args):     # *args 会把多传入的参数变成一个元组形式
print(name,age,args)

f1('fuyf',11, 'alex','eric') #传多个参数
li = [11, 22, 33] #定义列表
f1(li, 'servyou') #调用函数,将列表作为一个元组中一个元素
f1(*li, 'servyou') # 调用函数,将列表中每个元素作为元组中的一个元素
输出:

fuyf 11 ('alex', 'eric')
[11, 22, 33] servyou ()
11 22 (33, 'servyou')

=================================================================

def func(**kwargs):   # **kwargs 会把多传入的参数变成一个字典形式

    print(kwargs)

# 执行方式一

func(name='alex',age=18)

# 执行方式二

li = {'name':'fuyf','age':18, 'gender':'male'}

func(**li)

输出:

{'name': 'alex', 'age': 18}
{'gender': 'male', 'name': 'fuyf', 'age': 18}

====================================================================

万能参数:

def f1(*args, **kwargs):
print(args)
print(kwargs)

f1(11,22,33,k1='v1',k2='v2')

全局与局部变量

在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量。
全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序。
当全局变量与局部变量同名时:
在定义局部变量的子程序内,局部变量起作用;在其它地方全局变量起作用。
 
  全局变量:
     读,均可读
     赋值,global
     字典、列表,可修改
     全局变量用大写
def f1(a1,a2):
    return a1+a2

def f1(a1,a2):
    return a1*a2

ret = f1(8,8)
print(ret)
=======================================
def f1(a1):
     a1.append(999)
     print(a1)

li = [11,22,33]
f1(li)
print(li)
======================================
NAME = 'fuyf'
def f1():
    age =18
    global NAME   #表示NAME是全局变量
    NAME = 'fuyf2'
    print(age,NAME)
def f2():
    age =11
    print(age,NAME)
f1()
f2()

 练习:函数编程实现登录。

def login(username,password):
    """
    用于用户登录
    :param username: 用户输入的用户名
    :param password: 用户输入的密码
    :return: Ture表示登录成功,False表示登录失败
    """
    f = open('db','r')  # 同一路径下db文件中写入正确的用户名|密码,如:admin|123456
    for i in f:
         line_list = i.strip().split('|')
         if line_list[0] == username and line_list[1] == password:
             return True
    return False



def main():
     t = input('1:登录,2:注册')
     if t =='1':
         user = input('请输入用户名:')
         pwd = input('请输入密码:')
         r = login(user,pwd)
         if r:
             print('登录成功')
         else:
             print('登录失败')

main()

6.三元运算

三元运算(三目运算),是对简单的条件语句的缩写。

1
2
3
4
5
# 书写格式
 
result = 1 if 条件 else 2
 
# 如果条件成立,那么将 “值1” 赋值给result变量,否则,将“值2”赋值给result变量

学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:

1
2
3
4
5
6
7
8
# 普通条件语句
if 1 == 1:
    name = 'fuyf'
else:
    name = 'alex'
    
# 三元运算
name = 'fuyf' if 1 == 1 else 'alex'

7.lambda表达式

对于简单的函数,也存在一种简便的表示方式,即:lambda表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# ###################### 普通函数 ######################
# 定义函数(普通方式)
def func(arg):
    return arg + 1
    
# 执行函数
result = func(123)
    
# ###################### lambda ######################
    
# 定义函数(lambda表达式)
my_lambda = lambda arg : arg + 1
    
# 执行函数
result = my_lambda(123)

8.内置函数

部分函数使用练习:

#abs绝对值
n = abs(-1)
print(n)
0,None,'',[],{},() #布尔值为假
print(bool(None))
# 所有为真,才为真
n = all([1,2,3])
print(n)
#只要有真,就为真
n = any([0,None,3])
print(n)

print(bin(5)) #二进制
print(oct(9)) #八进制
print(hex(14))#十六进制

#uft-8 一个汉字三个字节
#gbk 一个汉字二个字节

s = '李晨'
#字符串转换字节类型
# bytes(要转换的字符串,按照什么编码)
n = bytes(s,encoding='utf-8')
print(n)
n = bytes(s,encoding='gbk')
print(n)

#编译python代码
compile()
#执行python代码,接收:代码或字符串
exec('7+8+9')
#执行表达式,并且获取结果
ret = eval('7+8+9')
print(ret)
#查看对象提供了哪些功能
print(dir(list))
help(list)

# r = divmod(97,10)
# print(r)
# print(r[0])
# print(r[1])
n1,n2 = divmod(100,10)
print(n1)
print(n2)

r = [1,1,23,4]
# 判断对象是否是某个类的实例
t = isinstance(r,list)
print(t)

# filter(函数,可迭代的对象)
li = [11,22,33,44,55]
result = filter(lambda a:a > 33,li)
print(list(result))
# map(函数,可迭代的对象)
li = [11,22,33,44,55]
result = map(lambda a:a + 100,li)
print(list(result))
s = '李晨'
print(len(s))
r = bytes(s,encoding='utf-8')
print(len(r))

r1 = ['李晨',11,22,33]
r2 = ['is',11,22,33]
r3 = ['大黑牛',11,22,33]
r = zip(r1,r2,r3)
# print(list(r))
temp = list(r)[0]
s = ' '.join(temp)
print(s)
# 输出:李晨 is 大黑牛

print(round(9.4)) #四舍五入

print(pow(2,4)) #求指数

li = [1,3,45,56]
print(max(li))
print(min(li))
print(sum(li))

print(hash('exleeeesdss'))

NAME = 'fuyf'
def f1():
a = 'jack'
b = 'eric'
print(globals())
print(locals())
f1()
生成随机验证码
#生成数字加字母组成的6位随机验证码
import  random
li = []
for i in range(6):
    r= random.randrange(0,5)
    if r == 1 or r == 3:
        num = random.randrange(0,10)
        li.append(str(num))
    else:
        temp = random.randrange(65, 91)
        c = chr(temp)
        li.append(c)
result = ''.join(li)
print(result)

open函数,该函数用于文件处理

操作文件时,一般需要经历如下步骤:

  • 打开文件
  • 操作文件
  • 关闭文件

一、打开文件

1
文件句柄 = open('文件路径''模式')

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读;   不存在则创建;存在则只追加内容;】

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

  • r+, 读写【可读,可写】 ----用的最多的
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

 "b"表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

二、文件操作

#打开文件
f = open('db','r') #只读
f = open('db','w') #只写,先清空原文件
f = open('db','x') #文件存在,报错;不存在,创建并写内容
f = open('db','a') #追加

f = open('db','r')
data = f.read()
print(data)
f = open('db','rb')
data = f.read()
print(data,type(data))
f = open('db','a',encoding='utf-8')
f.write('李晨')
f.close()
f = open('db','ab')
f.write(bytes('李杰',encoding='utf-8'))
f.close()

f = open('db','r+',encoding='utf-8')
#如果打开模式无b,则read 按照字符读取
data  = f.read()
# tell 当前指针所在的位置(字节)
print(f.tell())
# seek 调整当前指针的位置(字节)
f.seek(f.tell())
# 当前指针位置开始向后覆盖
f.write('888')
f.close()

#操作文件
#通过源码查看功能
f.read()  #无参数,读全部;有参数,有b按字节,无b按字符
f.tell()  #获取当前指针位置(字节)
f.seek()  #指针跳到指定位置(字节)
f.write() #写数据,有b 字节;无b 字符
f.close() #关闭文件
f.flush() #强制刷新到磁盘
f.readline() #仅读取一行
f.truncate() #截断,指针后的内容清空
#for循环文件对象 f=open()
for line in f:
    print(line)

#关闭文件
f.close()
with open('xb') as f:
    pass

三、管理上下文

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

1
2
3
with open('log','r') as f:
        
    ...

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

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

1
2
with open('log1') as obj1, open('log2') as obj2:
    pass

作业:

1、查看haproxy配置

2、修改haproxy配置

思路:读一行、写一行

global
        log 127.0.0.1 local2
        daemon
        maxconn 256
        log 127.0.0.1 local2 info
defaults
        log global
        mode http
        timeout connect 5000ms
        timeout client 50000ms
        timeout server 50000ms
        option  dontlognull

listen stats :8888
        stats enable
        stats uri       /admin
        stats auth      admin:1234

frontend oldboy.org
        bind 0.0.0.0:80
        option httplog
        option httpclose
        option  forwardfor
        log global
        acl www hdr_reg(host) -i www.oldboy.org
        use_backend www.oldboy.org if www

backend buy.oldboy.org
        server 100.1.7.1 100.1.7.90 weight 20 maxconn 3000
        
backend www.oldboy.org
        server 100.1.7.2 100.1.7.9 weight 20 maxconn 3000
haproxy配置文件

python实现代码:

def fetch(backend):
    result = [] #用于记录查询结果
    with open('ha.conf','r',encoding='utf-8') as f:  #以只读方式打开ha配置文件
        flag = False  #设置标志位
        for line in f:  #for循环对象f中的每一行
            if line.strip().startswith('backend') and line.strip() == "backend " + backend:  #如果遇到以backend关键字开头并且是:backend 用户输入的backend
                flag = True
                continue
            if flag and line.strip().startswith("backend"):
                flag = False
                break
            if flag and line.strip():
                result.append(line.strip())
    return result

# ret = fetch("buy.oldboy.org")
# print(ret)

def add(backend,record):
    # 先检查记录存不存在
    record_list = fetch(backend)
    if not record_list:
        # backend不存在
        with open('ha.conf','r') as old,open('new.conf','w') as new:
            for line in old:
                new.write(line)
            new.write('\nbackend '+ backend + '\n')
            new.write(' '*8 + record +'\n')
    else:
        #backend存在
        if record in record_list:
            # record已经存在则不做操作
            pass
        else:
            #backend存在,record不存在
            record_list.append(record)
            with open('ha.conf', 'r') as old, open('new.conf', 'w') as new:
                flag = False
                for line in old:
                    if line.strip().startswith('backend') and line.strip() == "backend " + backend:
                        flag = True
                        new.write(line)
                        for new_line in record_list:
                            new.write(' '*8 + new_line +'\n')
                        continue  #跳出本次循环
                    if flag and line.strip().startswith('backend'):
                        flag = False
                        new.write(line)
                        continue
                    if line.strip() and not flag:
                        # 有数据,并且为False,则读一行写一行
                        new.write(line)

add('buy.oldboy.org', 'server 100.1.7.99 100.1.7.39 weight 20 maxconn 30')
haproxy作业代码

9.函数递归

def func(n):
    n +=1
    if n > 4:
        return "end"
    return func(n)

r = func(1)
print(r)

利用函数编写如下数列:

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368...

def func(arg1, arg2):
    if arg1 == 0:
        print(arg1, arg2)
    arg3 = arg1 + arg2
    print(arg3)
    func(arg2,arg3)

func(0,1)

 

 

posted @ 2017-06-19 11:53  枫叶赋  阅读(611)  评论(0编辑  收藏  举报

友情链接:东小店 Copyright 2014-2020 枫叶赋 版权所有