python菜鸟教程例题笔记
import math
import random
import unicodedata 引入日历模块 import calendar 用于获取昨天日期 import datetime 实现秒表 import time
#引入url import re
import itertoolsclass cartesian (object ): count=0 def __init__ (self ): self._data_list=[] def add_data (self,data=[] ): self._data_list.append(data) def build (self ): for item in itertools.product(*self._data_list): print (item,end=" " ) self.count+=1 if self.count%16 ==0 : print () if __name__=="__main__" : car=cartesian() car.add_data([1 ,2 ,3 ,4 ]) car.add_data([5 ,6 ,7 ,8 ]) car.add_data([9 ,10 ,11 ,12 ]) car.build()
判断字符串是否存在子字符串 def check (string, sub_str ): if (string.find(sub_str) == -1 ): print ("不存在!" ) else : print ("存在!" ) string = "www.runoob.com" sub_str ="runoob" check(string, sub_str)
使用正则表达式提取字符串中的 URL import re def Find (string ): url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+' , string) return url string = 'Runoob 的网页地址为:https://www.runoob.com,Google 的网页地址为:https://www.google.com' print ("Urls: " , Find(string))
将字符串作为代码执行 def exec_code (): LOC = """ def factorial(num): fact=1 for i in range(1,num+1): fact = fact*i return fact print(factorial(5)) """ exec (LOC) exec_code()
字符串翻转 str ='Runoob' print (str [::-1 ])str ='Runoob' print ('' .join(reversed (str )))
中间是一个开区间,最右边表示方向
s="hyl ekil ylemertxe ma i" y=s[:3 :-1 ] print (y)
按键(key)或值(value)对字典进行排序
sorted (key_value)
sorted(key_value.items(), key = lambda kv:(kv[1], kv[0]))
- lis = [{ "name" : "Taobao" , "age" : 100 }, { "name" : "Runoob" , "age" : 7 }, { "name" : "Google" , "age" : 100 }, { "name" : "Wiki" , "age" : 200 }] > print ("列表通过 age 升序排序: " ) print (sorted (lis, key = lambda i: i['age' ]) )print ("\r" ) > print ("列表通过 age 和 name 排序: " ) print (sorted (lis, key = lambda i: (i['age' ], i['name' ])) )print ("\r" ) print ("列表通过 age 降序排序: " )print (sorted (lis, key = lambda i: i['age' ],reverse=True ) )
移除字典点键值(key/value)对。 test_dict = {"Runoob" : 1 , "Google" : 2 , "Taobao" : 3 , "Zhihu" : 4 } del test_dict['Zhihu' ] test_dict.pop('Zhihu' ) new_dict = {key:val for key, val in test_dict.items() if key != 'Zhihu' }
给定两个字典,然后将它们合并为一个字典。
dict2.update(dict1) //方法二 res = {**dict1, **dict2}
将字符串的时间转换为时间戳
a1 = “2019-5-10 23:40:00”
先转换为时间数组
timeArray = time.strptime(a1, “%Y-%m-%d %H:%M:%S”)
转换为时间戳
timeStamp = int(time.mktime(timeArray)) print(timeStamp)
格式转换 - 转为 /
a2 = “2019/5/10 23:40:00”
先转换为时间数组,然后转换为其他格式
timeArray = time.strptime(a2, “%Y/%m/%d %H:%M:%S”) otherStyleTime = time.strftime(“%Y/%m/%d %H:%M:%S”, timeArray) print(otherStyleTime)
获得当前时间
now = datetime.datetime.now() timeArray = time.localtime(now)
快速排序 def partition (arr, left, right ): i = left - 1 pivot = arr[right] for j in range (left, right): if arr[j] < pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1 ], arr[right] = arr[right], arr[i + 1 ] return i + 1 def quickSort (arr, left, right ): if left < right: p = partition(arr, left, right) quickSort(arr, left, p - 1 ) quickSort(arr, p + 1 , right) arr = [10 , 9 , 2 , 99 , 87 , 3 ] quickSort(arr, 0 , len (arr) - 1 ) print (arr)
归并 def merge (arr, l, m, r ): n1 = m - l + 1 n2 = r- m L = [0 ] * (n1) R = [0 ] * (n2) for i in range (0 , n1): L[i] = arr[l + i] for j in range (0 , n2): R[j] = arr[m + 1 + j] i = 0 j = 0 k = l while i < n1 and j < n2 : if L[i] <= R[j]: arr[k] = L[i] i += 1 else : arr[k] = R[j] j += 1 k += 1 while i < n1: arr[k] = L[i] i += 1 k += 1 while j < n2: arr[k] = R[j] j += 1 k += 1 def mergeSort (arr,l,r ): if l < r: m = int ((l+(r-1 ))/2 ) mergeSort(arr, l, m) mergeSort(arr, m+1 , r) merge(arr, l, m, r) arr = [12 , 11 , 13 , 5 , 6 , 7 ] n = len (arr) print ("给定的数组" ) for i in range (n): print ("%d" %arr[i]), mergeSort(arr,0 ,n-1 ) print ("\n\n排序后的数组" ) for i in range (n): print ("%d" %arr[i]),
计数排序 def countSort (arr ): output = [0 for i in range (256 )] count = [0 for i in range (256 )] ans = ["" for _ in arr] for i in arr: count[ord (i)] += 1 for i in range (256 ): count[i] += count[i-1 ] for i in range (len (arr)): output[count[ord (arr[i])]-1 ] = arr[i] count[ord (arr[i])] -= 1 for i in range (len (arr)): ans[i] = output[i] return ans arr = "wwwrunoobcom" ans = countSort(arr) print ( "字符数组排序 %s" %("" .join(ans)) )
计数排序plus版 def countSort (arr ): count = [ 0 for i in range (256 )] output = ["" for _ in arr] mx, mn = 0 , 255 for i in arr: idx = ord (i) if idx > mx: mx = idx if idx < mn: mn = idx count[idx] += 1 idx = 0 for i in range (mn, mx + 1 ): if count[i] == 0 : continue for _ in range (count[i]): output[idx] = chr (i) idx += 1 return output arr = "wwwrunoobcom" ans = countSort(arr) print ( "字符数组排序 %s" %("" .join(ans)) )
希尔排序 def shellSort (arr ): n = len (arr) gap = int (n/2 ) while gap > 0 : for i in range (gap,n): temp = arr[i] j = i while j >= gap and arr[j-gap] >temp: arr[j] = arr[j-gap] j -= gap arr[j] = temp gap = int (gap/2 ) arr = [ 12 , 34 , 54 , 2 , 3 ] n = len (arr) print ("排序前:" ) for i in range (n): print (arr[i]), shellSort(arr) print ("\n排序后:" ) for i in range (n): print (arr[i]),