“人生苦短,我用python”
python之禅:Simple is better than complex
(1)if语句
if 条件测试1:
\t语句1
elif 条件测试2:
\t语句2
else:
\t语句3
条件测试:
相等:==
不相等:!=
比较:< >
and 和 or 链接多个测试
in ; not in 判断特定值是否包含在列表中
列表是否为空
(2)for循环
列表遍历
for value in list:
\t语句
字典遍历
for value in dic:
\t语句
(3)while循环
while 条件测试:
\t语句
可使用break退出循环
使用continue退出本次循环
读取整个文件
with open(‘路径’) as file_object:
\t contents=file_object.read()
\t print(contents)
逐行读取
with open(‘路径’) as file_object:
\t for line in file_object:
\t print(line)
创建一个包含文件各行内容的列表
with open(‘路径’) as file_object:
\t lines=file_object.readlines()
\t for line in lines:
\t\t print(line.rstrip())
读取文件时,python将其中所有文本解读为字符串
写入文件
with open(‘路径’,‘w’) as file_object:
\t file_object.write(value)
写入多行
with open(‘路径’,‘w’) as file_object:
\t file_object.write(value\n)
\t file_object.write(value\n)
附加到文件
不会覆盖原有内容
with open(‘路径’,‘a’) as file_object:
\t file_object.write(value\n)
\t file_object.write(value\n)
#用到列表解析
def quicksort(arr):
'''快速排序法'''
if len(arr)<2:
return arr
else:
pivot=arr[0]
less=[i for i in arr[1:] if ipivot]
return quicksort(less)+[pivot]+quicksort(larger)
print(quicksort([1,5,3,2]))
#for循环
def findsmallest(arr):
'''找列表中最小值'''
smallest=arr[0]
smallest_index=0
for i in range(1,len(arr)):
if arr[i]
#while循环
def binary_search(list,item):
'''二分查找'''
low=0 #起点
high=len(list)-1 #终点
while high>=low:
mid=low+int((high-low)/2) #中间值
if item==list[mid]:
return mid
elif item>list[mid]:
low=mid+1;
else:
high=mid-1;
return None
list=[1,2,3,6,9,10]
print(str(binary_search(list,6)))
print(str(binary_search(list,4)))
#字典
from collections import deque
'''图的形成'''
graph={}
graph["you"]=["alice","bob","claire"]
graph["bob"]=["anuj","peggy"]
graph["alice"]=["peggy"]
graph["claire"]=["thom","jonny"]
graph["anuj"]=[]
graph["peggy"]=[]
graph["thom"]=[]
graph["jonny"]=[]
print(graph)
'''广度优先搜索'''
def person_is_seller(name):
'''定义一个供应商确定函数'''
return name[-1]=="m"
def BFsearch(name):
'''借助队列'''
search_queue = deque()
search_queue += graph[name]
searched = []
while search_queue:
person = search_queue.popleft()
if person not in searched:
'''判断是否重复'''
if person_is_seller(person):
print(person+" is a seller!")
return True
else:
'''否的话要将其朋友拉入队列'''
search_queue += graph[person]
searched.append(person)
return False
print(BFsearch("you"))