zoukankan      html  css  js  c++  java
  • 二、python基础(列表、元组、字符串、集合、字典、文件操作,函数基本语法及特性)

    本节内容

    1. 列表、元组操作
    2. 字符串、列表、字典、集合操作
    3. 文件操作
    4. 函数基本语法及特性

    一、列表、元组操作

    • 列表是我们最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作;
    • 列表操作:切片:取多个元素、追加、插入、修改、删除、扩展、拷贝、统计、排序&翻转、获取下标。
    • 元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表。

    二、 字符串、列表、字典、集合

    字符串:a='123'

    列表:b=['1','2','3']

    字典:c={'1':'abc','2':'def'}

    集合:d=set(a)

    三、文件操作

    对文件操作流程:

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

    打开文件的模式有:

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

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

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

    "U"表示在读取时,可以将 自动转换成 (与 r 或 r+ 模式同使用,将windows文件转换成linux文件的过程中使用)

    • rU
    • r+U

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

    • rb
    • wb
    • ab
    方式一:
    f=open("yesterday2","w+",encoding="utf-8")
    f.write("------add-----------
    ")
    f.write("------df-----------
    ")
    f.write("------dfasfasdf---------
    ")
    print(f.tell())  #显示文件中光标位置
    print(f.seek(0))  #将文件光标位置设置为文件开头
    print(f.readline())  #读取文件的一行内容
    f.write("------czk-----------") #在文件末尾写入内容
    f.close()  #关闭文件
    方式二:
    with open('yesterday2','w+',enconding='utf-8') as f:
      f.write('.......')

    四、函数基本语法及特性

    函数是什么?

    函数一词来源于数学,但编程中的「函数」概念,与数学中的函数是有很大不同的,编程中的函数在英文中也有很多不同的叫法。在BASIC中叫做subroutine(子过程或子程序),在Pascal中叫做procedure(过程)和function,在C中只有function,在Java里面叫做method。

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

    特性:

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

    函数参数与局部变量  

    形参变量只有在被调用时才分配内存单元,在调用结束时,即刻释放所分配的内存单元,因此,形参只在函数内部有效,函数调用结束返回主调用函数后则不能再使用该形参变量;

    实参可以是常量、变量、表达式、函数等,无论实参是何种类型的量,在进行函数调用时,它们都必须有确定的值,以便把这些值传送给形参,因此应预先用赋值,输入等办法使参数获得确定值。

    示例展示:

    # Author:daemon chai
    old_index = -1
    new_dict={}
    other_list=[]
    #将配置文件读取出来,需要修改的信息存储在字典里面
    with open("haproxy","r",encoding="utf-8") as f :
        for index,line in enumerate(f) :
            #存储配置文件中节点的bakend
            if line.strip().startswith("bakend") :
                old_index = index + 1
                user_name=line.strip().split()[1].split('.')[1]
                new_dict[user_name]={}
                new_dict[user_name]["bakend"]=line.strip().split()[1]
                name=line.strip().split()[1]
                # print(new_list[user_name])
            #存储节点信息的record
            elif old_index == index :
                new_dict[user_name]["record"]={}
                new_dict[user_name]["record"]["server"]=line.strip().split()[1]
                new_dict[user_name]["record"]["weight"] = line.strip().split()[3]
                new_dict[user_name]["record"]["maxconn"] = line.strip().split()[5]
            #存储其他不需要修改的信息
            else:
                other_list.append(line.strip())
    
    while True:
        print("请选择需要的功能".center(50,"="))
        #打印已有节点信息
        print("已有的节点:")
        for dict_one in new_dict:
            print(dict_one)
    #提供功能选择界面
        print("现有功能:
    c、查询;
    a、增加;
    r、修改;
    d、删除;
    q、退出。")
        choice = input("请选择你需要的功能:")
        #查询操作
        if choice =='c' :
            while True:
                choice_query = input("请输入查询的节点,退出(q):")
                if choice_query == "q":
                    break
                elif choice_query in new_dict:
                    print("节点名称:", new_dict[choice_query]["bakend"])
                    print("ip地址:", new_dict[choice_query]["record"]["server"])
                    print("权重:", new_dict[choice_query]["record"]["weight"])
                    print("连接数:", new_dict[choice_query]["record"]["maxconn"])
                else:
                    print("输入错误,请重新输入")
        #添加操作
        elif choice=='a':
            while True:
                add_simple_name = input("请输出节点简称")
                add_name = input("请输出节点名称")
                add_ip = input("请输出节点ip")
                add_weight = input("请输出节点权重")
                add_maxconn = input("请输出节点最大连接数")
                new_dict[add_simple_name]={}
                new_dict[add_simple_name]["bakend"] = add_name
                new_dict[add_simple_name]["record"] = {}
                new_dict[add_simple_name]["record"]["server"] = add_ip
                new_dict[add_simple_name]["record"]["weight"] = add_weight
                new_dict[add_simple_name]["record"]["maxconn"] = add_maxconn
                print("添加成功",new_dict[add_simple_name])
                break
        #修改节点信息操作
        elif choice == 'r':
            while True:
                return_name = input("你想修改哪个节点啊?退出(q)")
                if return_name == "q":
                    break
                elif return_name in new_dict:
                    new_dict[return_name]["bakend"] = input("请输出修改后节点名称(例如www.user.org)")
                    new_dict[return_name]["record"]["server"] = input("请输出修改后节点ip")
                    new_dict[return_name]["record"]["weight"] = input("请输出修改后节点权重")
                    new_dict[return_name]["record"]["maxconn"] = input("请输出修改后节点最大连接数")
                    print("保存退出后修改才会生效")
                    break
        #删除节点操作
        elif choice == 'd':
            while True:
                delete_name = input("你想删除那个节点呢,退出(q)?")
                if delete_name == "q":
                    break
                elif delete_name in new_dict:
                    del new_dict[delete_name]
                    print("删除成功!")
                else:
                    print("没有这个节点,重新输入!")
        #退出操作,将修改后的节点信息存储进文件
        elif choice == 'q':
            with open("haproxy", "w") as f1 :
                f1.write("")
            for i in other_list:
                with open("haproxy", "a") as f2 :
                    f2.write("%s
    "%i)
            for i in new_dict:
                with open("haproxy", "a") as f3 :
                    f3.write("bakend %s
    	server %s weight %s maxconn %s
    
    "
                             %(new_dict[i]["bakend"], new_dict[i]["record"]["server"], new_dict[i]["record"]["weight"],
                               new_dict[i]["record"]["maxconn"]))
            print("退出程序成功")
            break
        else:
            print("输入错误,请重新输入
    ")

     递归函数二分查找示例:

    data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]
     
     
    def binary_search(dataset,find_num):
        print(dataset)
     
        if len(dataset) >1:
            mid = int(len(dataset)/2)
            if dataset[mid] == find_num:  #find it
                print("找到数字",dataset[mid])
            elif dataset[mid] > find_num :# 找的数在mid左面
                print("33[31;1m找的数在mid[%s]左面33[0m" % dataset[mid])
                return binary_search(dataset[0:mid], find_num)
            else:# 找的数在mid右面
                print("33[32;1m找的数在mid[%s]右面33[0m" % dataset[mid])
                return binary_search(dataset[mid+1:],find_num)
        else:
            if dataset[0] == find_num:  #find it
                print("找到数字啦",dataset[0])
            else:
                print("没的分了,要找的数字[%s]不在列表里" % find_num)
     
     
    binary_search(data,66)
    

    内置函数参考网址:https://docs.python.org/3/library/functions.html?highlight=built#ascii 

    内置函数使用注意事项:

    #compile
    f = open("函数递归.py")
    data =compile(f.read(),'','exec')
    exec(data)
    
    
    #print
    msg = "又回到最初的起点"
    f = open("tofile","w")
    print(msg,"记忆中你青涩的脸",sep="|",end="",file=f)
    
    
    # #slice
    # a = range(20)
    # pattern = slice(3,8,2)
    # for i in a[pattern]: #等于a[3:8:2]
    #     print(i)
    #
    #
    
    
    #memoryview
    #usage:
    #>>> memoryview(b'abcd')
    #<memory at 0x104069648>
    #在进行切片并赋值数据时,不需要重新copy原列表数据,可以直接映射原数据内存,
    import time
    for n in (100000, 200000, 300000, 400000):
        data = b'x'*n
        start = time.time()
        b = data
        while b:
            b = b[1:]
        print('bytes', n, time.time()-start)
    
    for n in (100000, 200000, 300000, 400000):
        data = b'x'*n
        start = time.time()
        b = memoryview(data)
        while b:
            b = b[1:]
        print('memoryview', n, time.time()-start)
    
    
    

      

    逆风的方向最适合飞翔,我不怕千万人阻挡,只怕自己投降。
  • 相关阅读:
    WPF FAQ (from Syncfusion)
    父窗口与子窗口的层次关系
    [WPF疑难]如何禁用WPF窗口的系统菜单(SystemMenu)
    【讨论】不得不重视的问题:信息太多!信息太杂!
    javaScript系列 [08]javaScript和JSON (进阶)
    javaScript系列 [11]Canvas绘图(路径)
    javaScript系列 [10]Canvas绘图(基础)
    Hexo + Github搭建个人博客
    javaScript系列 [07]日期类型和计时器
    javaScript系列 [09]javaScript和JSON (拓展)
  • 原文地址:https://www.cnblogs.com/daemon-czk/p/6696811.html
Copyright © 2011-2022 走看看