二、python基础(列表、元组、字符串、集合、字典、文件操作,函数基本语法及特性)...
本節(jié)內(nèi)容
一、列表、元組操作
- 列表是我們最常用的數(shù)據(jù)類型之一,通過列表可以對(duì)數(shù)據(jù)實(shí)現(xiàn)最方便的存儲(chǔ)、修改等操作;
- 列表操作:切片:取多個(gè)元素、追加、插入、修改、刪除、擴(kuò)展、拷貝、統(tǒng)計(jì)、排序&翻轉(zhuǎn)、獲取下標(biāo)。
- 元組其實(shí)跟列表差不多,也是存一組數(shù),只不是它一旦創(chuàng)建,便不能再修改,所以又叫只讀列表。
?
二、 字符串、列表、字典、集合
字符串:a='123'
列表:b=['1','2','3']
字典:c={'1':'abc','2':'def'}
集合:d=set(a)
三、文件操作
對(duì)文件操作流程:
?
打開文件的模式有:
- r,只讀模式(默認(rèn))。
- w,只寫模式【不可讀,不存在則創(chuàng)建,存在則刪除內(nèi)容】
- a,追加模式【可讀,不存在則創(chuàng)建,存在則只追加內(nèi)容】
"+" 表示可以同時(shí)讀寫某個(gè)文件
- r+,可讀寫文件。【可讀、可寫、可追加】
- w+,寫和讀
- a+,同a
"U"表示在讀取時(shí),可以將 \r \n \r\n自動(dòng)轉(zhuǎn)換成 \n (與 r 或 r+ 模式同使用,將windows文件轉(zhuǎn)換成linux文件的過程中使用)
- rU
- r+U
"b"表示處理二進(jìn)制文件(如:FTP發(fā)送上傳ISO鏡像文件,linux可忽略,windows處理二進(jìn)制文件時(shí)需標(biāo)注)
- rb
- wb
- ab
方式二:
with open('yesterday2','w+',enconding='utf-8') as f:
f.write('.......')
四、函數(shù)基本語(yǔ)法及特性
函數(shù)是什么?
函數(shù)一詞來源于數(shù)學(xué),但編程中的「函數(shù)」概念,與數(shù)學(xué)中的函數(shù)是有很大不同的,編程中的函數(shù)在英文中也有很多不同的叫法。在BASIC中叫做subroutine(子過程或子程序),在Pascal中叫做procedure(過程)和function,在C中只有function,在Java里面叫做method。
定義: 函數(shù)是指將一組語(yǔ)句的集合通過一個(gè)名字(函數(shù)名)封裝起來,要想執(zhí)行這個(gè)函數(shù),只需調(diào)用其函數(shù)名即可
特性:
函數(shù)參數(shù)與局部變量
形參變量只有在被調(diào)用時(shí)才分配內(nèi)存單元,在調(diào)用結(jié)束時(shí),即刻釋放所分配的內(nèi)存單元,因此,形參只在函數(shù)內(nèi)部有效,函數(shù)調(diào)用結(jié)束返回主調(diào)用函數(shù)后則不能再使用該形參變量;
實(shí)參可以是常量、變量、表達(dá)式、函數(shù)等,無(wú)論實(shí)參是何種類型的量,在進(jìn)行函數(shù)調(diào)用時(shí),它們都必須有確定的值,以便把這些值傳送給形參,因此應(yīng)預(yù)先用賦值,輸入等辦法使參數(shù)獲得確定值。
示例展示:
# Author:daemon chai old_index = -1 new_dict={} other_list=[] #將配置文件讀取出來,需要修改的信息存儲(chǔ)在字典里面 with open("haproxy","r",encoding="utf-8") as f :for index,line in enumerate(f) :#存儲(chǔ)配置文件中節(jié)點(diǎn)的bakendif line.strip().startswith("bakend") :old_index = index + 1user_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])#存儲(chǔ)節(jié)點(diǎn)信息的recordelif 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]#存儲(chǔ)其他不需要修改的信息else:other_list.append(line.strip())while True:print("請(qǐng)選擇需要的功能".center(50,"="))#打印已有節(jié)點(diǎn)信息print("已有的節(jié)點(diǎn):")for dict_one in new_dict:print(dict_one) #提供功能選擇界面print("現(xiàn)有功能:\nc、查詢;\na、增加;\nr、修改;\nd、刪除;\nq、退出。")choice = input("請(qǐng)選擇你需要的功能:")#查詢操作if choice =='c' :while True:choice_query = input("請(qǐng)輸入查詢的節(jié)點(diǎn),退出(q):")if choice_query == "q":breakelif choice_query in new_dict:print("節(jié)點(diǎn)名稱:", new_dict[choice_query]["bakend"])print("ip地址:", new_dict[choice_query]["record"]["server"])print("權(quán)重:", new_dict[choice_query]["record"]["weight"])print("連接數(shù):", new_dict[choice_query]["record"]["maxconn"])else:print("輸入錯(cuò)誤,請(qǐng)重新輸入")#添加操作elif choice=='a':while True:add_simple_name = input("請(qǐng)輸出節(jié)點(diǎn)簡(jiǎn)稱")add_name = input("請(qǐng)輸出節(jié)點(diǎn)名稱")add_ip = input("請(qǐng)輸出節(jié)點(diǎn)ip")add_weight = input("請(qǐng)輸出節(jié)點(diǎn)權(quán)重")add_maxconn = input("請(qǐng)輸出節(jié)點(diǎn)最大連接數(shù)")new_dict[add_simple_name]={}new_dict[add_simple_name]["bakend"] = add_namenew_dict[add_simple_name]["record"] = {}new_dict[add_simple_name]["record"]["server"] = add_ipnew_dict[add_simple_name]["record"]["weight"] = add_weightnew_dict[add_simple_name]["record"]["maxconn"] = add_maxconnprint("添加成功",new_dict[add_simple_name])break#修改節(jié)點(diǎn)信息操作elif choice == 'r':while True:return_name = input("你想修改哪個(gè)節(jié)點(diǎn)啊?退出(q)")if return_name == "q":breakelif return_name in new_dict:new_dict[return_name]["bakend"] = input("請(qǐng)輸出修改后節(jié)點(diǎn)名稱(例如www.user.org)")new_dict[return_name]["record"]["server"] = input("請(qǐng)輸出修改后節(jié)點(diǎn)ip")new_dict[return_name]["record"]["weight"] = input("請(qǐng)輸出修改后節(jié)點(diǎn)權(quán)重")new_dict[return_name]["record"]["maxconn"] = input("請(qǐng)輸出修改后節(jié)點(diǎn)最大連接數(shù)")print("保存退出后修改才會(huì)生效")break#刪除節(jié)點(diǎn)操作elif choice == 'd':while True:delete_name = input("你想刪除那個(gè)節(jié)點(diǎn)呢,退出(q)?")if delete_name == "q":breakelif delete_name in new_dict:del new_dict[delete_name]print("刪除成功!")else:print("沒有這個(gè)節(jié)點(diǎn),重新輸入!")#退出操作,將修改后的節(jié)點(diǎn)信息存儲(chǔ)進(jìn)文件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\n"%i)for i in new_dict:with open("haproxy", "a") as f3 :f3.write("bakend %s\n\tserver %s weight %s maxconn %s\n\n"\%(new_dict[i]["bakend"], new_dict[i]["record"]["server"], new_dict[i]["record"]["weight"],\new_dict[i]["record"]["maxconn"]))print("退出程序成功")breakelse:print("輸入錯(cuò)誤,請(qǐng)重新輸入\n")?遞歸函數(shù)二分查找示例:
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 itprint("找到數(shù)字",dataset[mid])elif dataset[mid] > find_num :# 找的數(shù)在mid左面print("\033[31;1m找的數(shù)在mid[%s]左面\033[0m" % dataset[mid])return binary_search(dataset[0:mid], find_num)else:# 找的數(shù)在mid右面print("\033[32;1m找的數(shù)在mid[%s]右面\033[0m" % dataset[mid])return binary_search(dataset[mid+1:],find_num)else:if dataset[0] == find_num: #find itprint("找到數(shù)字啦",dataset[0])else:print("沒的分了,要找的數(shù)字[%s]不在列表里" % find_num)binary_search(data,66)內(nèi)置函數(shù)參考網(wǎng)址:https://docs.python.org/3/library/functions.html?highlight=built#ascii?
內(nèi)置函數(shù)使用注意事項(xiàng):
#compile f = open("函數(shù)遞歸.py") data =compile(f.read(),'','exec') exec(data)#print msg = "又回到最初的起點(diǎn)" 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> #在進(jìn)行切片并賦值數(shù)據(jù)時(shí),不需要重新copy原列表數(shù)據(jù),可以直接映射原數(shù)據(jù)內(nèi)存, import time for n in (100000, 200000, 300000, 400000):data = b'x'*nstart = time.time()b = datawhile b:b = b[1:]print('bytes', n, time.time()-start)for n in (100000, 200000, 300000, 400000):data = b'x'*nstart = time.time()b = memoryview(data)while b:b = b[1:]print('memoryview', n, time.time()-start)
轉(zhuǎn)載于:https://www.cnblogs.com/daemon-czk/p/6696811.html
總結(jié)
以上是生活随笔為你收集整理的二、python基础(列表、元组、字符串、集合、字典、文件操作,函数基本语法及特性)...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Caffe学习笔记(4)--------
- 下一篇: .Net 中HashTable,Hash