2018.10.15——10.21

《Python編程從入門到實踐》

(實際這篇文章延後了整整一週才完成 )

第三章 列表簡介

這裏爲了提高完整性,加入第3章 列表簡介的內容。

列表聲明:bicycles = [] ; bicycles[‘trek’,‘specialized’ …]

訪問列表:
bicycles[0],bicycles[1]… bicycles[-1]//訪問最後一個元素 bicycles[-2]//訪問倒數第二個。。。
操作列表元素使大寫,小寫和title:bicycles[0].upper() bicycles[0].lower() bicycles[0].title()

在列表中添加元素:
1.在列表尾添加:bicycles.append(‘suzuki’)
2.在任何位置添加 bicycles.insert(0,‘suzuki’) //前者爲索引0表示第一個位置

刪除元素:
1.del bicycles[索引] //del語句
2.poped = bicycles.pop(索引可選)//默認彈出列表末尾元素,且值可以取到存在poped
3.bicycles.remove(‘suzuki’) //根據值來刪除,若其中有多個相同值,只能刪一個,想要全部刪除用for循環

1.cars.sort() 永久性排序
2.sorted(cars) sorted方法臨時排序
//按首字母小寫字母abcdef…排序,均可加入 reverse = True 進行倒排
cars .reverse() 直接倒排,永久性,但可再調用一次恢復

第四章 操作列表

遍歷列表:for dog in dogs:
…//python不用括號靠縮進體現結構
函數range(1,5,2)//生成一系列數字1表示從1開始,5表示到4結束,2表示步長爲2,所以生成1,3
函數 list()//將range()生成的數字存入列表 爲數字列表 例:digits = list(range(1,5,2)) 對於數字列表有min(digits) max(…) sum(…)
列表解析:

squares = [value**2 for value in range(1,11)]`
//等同於以下三行 
squares = [] 
for value in range(1,11):
 	squares.append(value**2) 

切片:
players[1,4]//第2個元素到第4個元素;
players[,4]//第1個元素到第4個元素;
players[1,]//第2個到最後一個元素;
players[-3,]//最後3個元素
複製列表:
friend_foods = my_foods//錯,只是將friend_foods關聯到my_foods的列表
正確複製語句:friend_foods = my_foods[:]

元組:類比列表用()標識,元組中的值定下來後不能再被修改 若要修改只能重新定義

第五章

if語句
if ==/!=/>/</>=/<=/in/not in :
elif:
elif:

else:

第六章 字典

聲明:a ={‘k1’:‘v1’,‘k2’:v2}//v2爲int
訪問:a.[‘k1’]
添加: a.[‘k3’] = ‘v3’ #修改同理
刪除: del a.[‘k3’]

字典遍歷:

for k,v in a.**items()**
for k in a.**keys()** #for k in sorted(a.keys()) 按首字母abcd..排序
for v in a.**values()**#for v in set(a.values()) 去除其中重複的元素

字典列表

aliens = [{'color':'yellow','speed':'slow'} for alien in range(30)]
for alien in aliens[:5]:
	print(alien)

字典中儲存列表:

favorate_places = {
 	'Tom':['tibet','Japan'],
 	'Kate':['China'],
 	'Jack':['a','b','c'],
 	}
for name,places in favorate_places.items():
 	if len(places) == 1:
 		print(name + " favorate place is " + places[0].title())
 	else:
 		print(name + " favorate places are " )
 		for place in places:
			print(place.title())

第七章 用戶輸入和while循環

age = input(“Tell me your age please?”)
#如果之後你想對age進行數字操作(如比較大小),需要age= int(age)
while …:
break
continue

第八章 函數

tips:給一個形參設默認值時一定要設置在沒有默認值的形參後面
傳遞列表:def function_name(list_name)
想不改變原來的列表,即只傳副本:
def function_name(list_name[:])

def a(*b) #*b接受若干值(元組)
def build_carinfo(model,manufacture,**car_infos):#**car_infos接受若干鍵值對(字典)
 	info = {}
 	info['Model'] = model
 	info['Manufacture'] = manufacture
 	for key,value in car_infos.items():
 		info[key] = value
 	return info
 car = build_carinfo('subaru','outback',color = 'blue',tow_package = True,acceleration = 10)
 print(car)

import module_name
import module_name as mn

調用其中函數時:module_name.function_name()

from module_name import function_name (as fn)
from module_name import * #會導入所有函數,不推薦

第九章 類

def __ init (self,a,b):
super.
init __(self,a,b)
new1 = …/class_name()
new2 = …

導入方式和函數導入方式基本一致

第十章 文件和異常

直接讀取整個文件
read()

with open('pi_digits.txt') as file_object:
	contends = file_object.read()
	print(contends.rstrip())

逐行遍歷文件

with open('pi_digits.txt') as file_object:
	for line in file_object:
		print(line.strip())

創建一個包含文件各行內容的列表在with塊外使用

readlines()

with open('pi_digits.txt') as file_object:
	lines = file_object.readlines()
for line in lines:
	print(line.strip())


tips:1.write(“…\n”)
2.with open(file_name,‘w’)#默認是r 讀,a是附加,w是覆蓋寫,r+是讀寫

異常
關注點:split()#劃分單詞
try:
。。。
except 某種error:
pass(不做任何處理)
else:
#正常邏輯代碼

def count_words(filename):
 	"""Count how many words a file include""" 
 	try:
 		with open(filename) as file_object:
 			contends = file_object.read()
 	except FileNotFoundError:
 		pass
 	else:
 		words = contends.split()
 		words_num = len(words)
 		print("The "+filename+" has about "+str(words_num)+" words.")

 filenames = ['alice.txt','sadaasbjfehr.txt','kajbcavufbaef.rtf.word','pi_digits.txt']
 for filename in filenames:
 	count_words(filename)

存儲數據
存入文件:json.dump()

	username = input("What's your name?")
	filename = 'username.json'
with open(filename,'w') as f_obj:
	json.dump(username,f_obj)

讀取文件:json.load()

def jkasnx():
	filename = 'username.json'
	try:
		with open(filename) as f_obj:
			username = json.load(f_obj)
	except FileNotFoundError:
		pass #return None
	else:
		return username

代碼重構(理解):

def greet_user():
	filename = 'username.json'
	try:
		with open(filename) as f_obj:
			username = json.load(f_obj)
	except FileNotFoundError:
		username = input("What is your name?")
		with open(filename,'w') as f_obj:
			json.dump(username,f_obj)
		print("We will remmember you when you come back,"+username.title()+".") 
	else:
		print("Welcome back : "+username.title())
def get_stored_username():
	filename = 'username.json'
	try:
		with open(filename) as f_obj:
			username = json.load(f_obj)
	except FileNotFoundError:
		pass #return None
	else:
		return username

def get_new_user_name():
	username = input("What's your name?")
	filename = 'username.json'
	with open(filename,'w') as f_obj:
		json.dump(username,f_obj)
		return username

def greet_user():
	username = get_stored_username()
	if username:
		print("Welcome back : "+username.title())
	else:
		username = get_new_user_name()
		print("We will remmember you when you come back,"+username.title()+".")

第十一章 測試

tips:
1.import unittest
2.繼承unittext.TestCase
3.調用斷言函數測試:p193
常用:assertEqual(a,b);assertIn(item,list)
4.def setUp(self)創建一組要進行測試的數據、答案
#不用再在每個單元測試裏分別聲明測試類和答案

《Spring Boot實戰》

第一章 入門

創建了一個springboot框架

《 Java核心技術(卷1)》

leetcode

W3CSchool

總結

just do it.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章