日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python 命令汇总

發布時間:2023/12/13 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 命令汇总 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

python 庫windows安裝


兵種:python程序員。
等級:二級。
攻擊:較高。
防御:普通。
價格:低。
天賦:膠水,我方有c程序員時,速度可達到c程序員的80%。
天賦:成熟,難以升級到三級,即使成功也沒什么好處
—–劉鑫Mars


#Types


a = 2 # integer b = 3.0 # float c = 5.3e5 #exponential d = 6.5 + 0.5j # complex e = 7 > 5 # boolean f = 'helloword' # string

# Lists


a = ['red', 'blue', 'green'] b = list(range(5)) c = [nu**2 for nu in b] d = [nu**2 for nu in b if nu <3] e = c[0] f = c[1:2] g = ['re', 'bl'] + ['gr'] h = ['re']*5 ['re','bl'].index('re') #returns index of 're' 're' in ['re', 'bl'] #true if 're' in list sorted([3,4,1]) #returns sorted list---- 列表中的元素可以是相同的類型,也可以是不同類型的。 a =[1, "b", 3, 6, "google", True]-----列表中插入或者刪除元素----- a.insert(3, "fire") #插入到類別中第四個位置 a.append("ch") # 插入到列表的最后面 del a[2]     #刪除列表中的第三個元素['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 重復 列表操作包含以下函數: 1、cmp(list1, list2):比較兩個列表的元素 2、len(list):列表元素個數 3max(list):返回列表元素最大值 4min(list):返回列表元素最小值 5list(seq):將元組轉換為列表 列表操作包含以下方法: 1list.append(obj):在列表末尾添加新的對象 2list.count(obj):統計某個元素在列表中出現的次數 3list.extend(seq):在列表末尾一次性追加另一個序列中的多個值(用新列表擴展原來的列表) 4list.index(obj):從列表中找出某個值第一個匹配項的索引位置 5list.insert(index, obj):將對象插入列表 6list.pop(obj=list[-1]):移除列表中的一個元素(默認最后一個元素),并且返回該元素的值 7list.remove(obj):移除列表中某個值的第一個匹配項 8list.reverse():反向列表中元素 9list.sort([func]):對原列表進行排序

Tuple


元組是不能增加或刪除元素,類似于常量。
(2,) #一個元素的元組


# Dictionaries


字典是一種映射,從key 到value 的一種映射。

a = {'red': 'rouge', 'blue':'bleu', 'green': 'vertet'} b = a['red'] #字典取值 c = [value for key, value in a.items()] d = a.get('yellow', 'no translation found')

#Strings


字符串其實是一個特殊的列表,列表中每個元素是一個字符。字符串本質上是一個常量,可以查詢,不能修改。

a = 'red' char = a[2] 'red' + 'blue' '1, 2, three'.split(',') # split string into list '.'.join(['1', '2', 'three']) # concatenate list into string

%占位符
a = “hello %s” % “wang”
a =”%s %s” % (“hello”, “wang”)
a =”%(verb)s %(name)s” % {“verb”: “hello”, “name” : “wang”} #占位符命名


# Operators


a = 3 print(a) a += 1 #(*=, /=) print(a) a *= 1 print(a) a /= 1 print(a) 3 + 2 3/2 3//2 #integer division 3*2 3**2 # exponent 3%2 # remainder abs(a) # absolute value 1 == 1 # equal 2 >1 2 <1 1 != 2 #not equal 1 != 2 and 2 < 3 # logical AND 1 != 2 or 2 < 3 #logical OR not 1 == 2 # logical NOT 'a' in b # test if a is in b a is b # test if objects point to the same memory----簡寫---- a = a +1 等價于 a +=1 a = a-1 等價于 a -=1

#Control Flow


控制流是能夠改變代碼執行順序的。

# if/elif/else a, b = 1, 2 if a + b == 3:print('True') elif a + b == 1:print('False') else:print('?')# for a = ['red', 'blue', 'green'] for color in a:print(color)#while number = 1 while number < 10:print(number)number += 1-----while ----- while 條件:do something停止辦法: 改變條件,使得條件變False 使用 break 強制退出。#break number = 1 while True:print(number)number += 1if number > 10:break#Continue for i in range(20):if i%2 == 0:continueprint(i)------breakcontinue ------- row =[1, 2, 4, 6, 8] for item in row:if item ==2:     continue        #跳過后面兩句,只是跳出本次循環。if item == 4:break         #break使整個for 循環結束

# Functions, Classes, Generators, Decorators


所謂函數,就是多個命令的組合體。

# Function def myfunc(a1, a2):return a1 + a2x = myfunc(a1, a2)# Class class Point(object):def _init_(self, x):self.x = xdef _call_(self):print(self.x)x = Point(3)---類與對象 --- 類與對象,類似于 概念與實體# Generators def firstn(n):num = 0while num < n:yield numnum += 1#Consume the generator wiht list comprehension x = [i for i in firstn(10)]# Decorators class myDecorator(object):def _init_(self, f):self.f = fdef _call_(self):print("call")self.f()@myDecorator def my_funct():print('func')my_funct()

函數中的參數

形參: 
def clean_room(room_name):
clean_table(room_name)
clean_floor(room_name)
clear_trash(room_name)

clean_room(“主臥”)

位置參數: 依據位置賦值。
def clean_room(room_name, level):
# clear code

clean_room(“主臥”, 2)

關鍵字參數: 明確指出傳入給某個參數。
def clean_room(room_name, level):
#clean code

clean_room(level = 2, room_name =”主臥”)
關鍵字參數不局限位置信息。

默認參數: 
def clean_room(room_name, level =2):
#clean code

clean_room(“主臥”)

返回值: 
def clean_room(room_name, level =2):
#clean code
finished = True
return finished

success = clean_room(room_name =”主臥”)
無return 語句,默認返回 None.

多返回值: 
def clean_room(room_name, level =2):
#clean code
finished = True
error_msg = “清潔劑沒有了”
return finished, error_msg

success, msg = clean_room(room_name =”主臥”)
無return 語句,默認返回 None.

文檔字符串: 
def clean_room(room_name, level =2):
”’
這個函數用來清理房間  #文檔字符串
”’
#clean code
finished = True
error_msg = “清潔劑沒有了”
return finished, error_msg

success, msg = clean_room(room_name =”主臥”)
無return 語句,默認返回 None.


# IPython


# Python console<object>? # Information about the object <object>.<TAB> # tab completion# measure runtime of a function: %timeit range(1000) 100000 loops, best of 3: 7.76 us per loop# run scripts and debug %run %run -d # run in debug mode %run -t # measures execution time %run -p # ruans a profiler %debug # jumps to debugger after an exception%pdb # run debugger automatically on exception # examine history %history %history ~1/1-5 # lines 1-5 of last session# run shell commands !make # prefix command with "!"#clean namespace %reset

查看Python軟件包信息


可以查看已經安裝的python軟件包和版本

pip freeze   pip list

查看軟件包源代碼所在位置

python import xgboost xgboost.__file__ #查看xgboost包的__init__.py文檔所在位置

查看軟件包的版本

import xgboost xgboost.__version__

或者

pip show xgboost

不同軟件包的屬性不一樣,有的查詢版本可使用

import django django.VERSION

查看模塊的屬性
本質上是一個變量。

import xgboost dir(xgboost) ['Booster', 'DMatrix', 'VERSION_FILE', 'XGBClassifier', 'XGBModel', 'XGBRegressor', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', 'absolute_import', 'callback', 'compat', 'core', 'cv', 'libpath', 'os', 'plot_importance', 'plot_tree', 'plotting', 'rabit', 'sklearn', 'to_graphviz', 'train', 'training']

查看模塊的屬性類型

import xgboost dir(xgboost) type(xgboost.plotting)

模塊導入


模塊被導入時,代碼會運行一次。再次導入,不會再次運行。


規則1.模塊導入


跟入口文件在同一個目錄下。


規則2.模塊導入


. 表示當前模塊所在的包下。
.. 表示當前模塊的所在包的外層目錄下。


python命名規則


命名只能是數字、字母和下劃線。數字不能開頭,區分大小寫。


寫入文件


poem = '''\ Programming is fun When the work is done If you want to make your work also fun: use Python! ''' f = open('poem.txt','w') # 模式:'w'寫入 write,'r'讀取read,'a'追加 append #open 返回的是文件夾表示符 f.write(poem) # write text to file f.close() #close the file 不關閉會占用系統。

讀取文件


f = open('poem.txt')  #默認為'r'模式 while True:line = f.readline()if len(line) ==0:#空行表示讀取結束breakprint(line, end="")#print 內容后面默認會增加一個\n#這里end禁止結尾增加\n,改為增加"" f.close() #close the file

with語句


寫入文件

with open('poem.txt','w') as f:f.write(poem)

讀取文件

with open('poem.txt') as f:while True:line = f.readline()if len(line) == 0:breakprint(line, end="")

異常處理


try:一段可能出錯的代碼 expect ValueError as e:print(e) # 處理這個異常 except Exception:處理其余所有的異常 else: 沒有異常的處理代碼 try:一段可能出錯的代碼 finally:最后一定會執行的代碼,例如f.close() try:int("a") except ValueError as e:print(e)raise e # 拋出異常

python函數


Python lower()方法

描述

Python lower() 方法轉換字符串中所有大寫字符為小寫。

#!/usr/bin/pythonstr = "THIS IS STRING EXAMPLE....WOW!!!";print str.lower(); this is string example....wow!!!

Python清空指定文件夾下所有文件的方法

import shutil shutil.rmtree('要清空的文件夾名') os.mkdir('要清空的文件夾名')

python shutil模塊學習

python判斷文件和文件夾是否存在、創建文件夾

#判斷是否存在路徑 import os, shutil if os.path.exists('/home/bids/test/wang'):shutil.rmtree('/home/bids/test/wang')os.makedirs('/home/bids/test/wang')else:os.makedirs('/home/bids/test/wang') #判斷是否為文件 os.path.isfile('/home/bids/test/a.py') True os.path.isfile('/home/bids/test') False #判斷是否為目錄 #os.path.isdir()函數判斷某一路徑是否為目錄。 #其函數原型如下所示: os.path.isdir(path) #其參數 path為 要進行判斷的路徑。如果是則返回TRUE,否則返回FALSE

創建多級目錄

1.mkdir( path [,mode] )作用:創建一個目錄,可以是相對或者絕對路徑,mode的默認模式是0777。如果目錄有多級,則創建最后一級。如果最后一級目錄的上級目錄有不存在的,則會拋出一個OSError。2.makedirs( path [,mode] )作用: 創建遞歸的目錄樹,可以是相對或者絕對路徑,mode的默認模式也是0777。如果子目錄創建失敗或者已經存在,會拋出一個OSError的異常,Windows上Error 183即為目錄已經存在的異常錯誤。如果path只有一級,與mkdir一樣。

刪除目錄及多級目錄

#os.rmdir()函數刪除目錄。 #其原型如下所示: os.rmdir(path) #其參數path 為要刪除的目錄的路徑。 #注意:要刪除的目錄必須是空目錄 #os.removedirs()函數刪除多級目錄。 #其原型如下所示: os.removdirs(path) #其參數path 為要刪除的多級目錄的路徑。 #注意:要刪除的目錄必須是空目錄shutil.rmtree(path) #空目錄、有內容的目錄都可以刪,但只刪除最后一級目錄

Python執行系統命令

#os.system()result = os.system('cat /proc/cpuinfo') #linux result = os.system('ipconfig') #windows #os.popenoutput = os.popen('cat /proc/cpuinfo') print output.read() output.close() #commands.getstatusoutput()(status, output) = commands.getstatusoutput('cat /proc/cpuinfo') print status, output output.close()

%matplotlib inline是jupyter notebook里的命令, 意思是將那些用matplotlib繪制的圖顯示在頁面里而不是彈出一個窗口.
magic函數分兩種:一種是面向行的,另一種是面向單元型的。


python常用函數


# 查看當前工作目錄 retval = os.getcwd()

os.chdir() 方法用于改變當前工作目錄到指定的路徑

語法 chdir()方法語法格式如下: os.chdir(path) 參數path -- 要切換到的新路徑。 返回值 如果允許訪問返回 True , 否則返回False

shuffle() 方法將序列的所有元素隨機排序

#以下是 shuffle() 方法的語法: import random random.shuffle (lst ) 注意:shuffle()是不能直接訪問的,需要導入 random 模塊,然后通過 random 靜態對象調用該方法 shutil.copy(src,dst) #復制文件的內容以及權限,先copyfile后copymode#copy training data c=0 train_label={}os.mkdir("/home/bids/miscellaneous/project/test/Xvision-master20171024/DeepLearning/final_train_images_calc_nodule_only") for i in train_list:#print ishutil.copy('/home/bids/miscellaneous/project/test/Xvision-master20171024/scraper/data/'+i+'.png', '/home/bids/miscellaneous/project/test/Xvision-master20171024/DeepLearning/final_train_images_calc_nodule_only/'+str(c)+'.png')train_label[c] = new_image_dict[i]c+=1

python之模塊之shutil模塊


檢查軟件版本


from __future__ import print_function from distutils.version import LooseVersion as Version import sysOK = '\x1b[42m[ OK ]\x1b[0m' FAIL = "\x1b[41m[FAIL]\x1b[0m"try:import importlib except ImportError:print(FAIL, "Python version 3.4 (or 2.7) is required,"" but %s is installed." % sys.version)def import_version(pkg, min_ver, fail_msg=""):mod = Nonetry:mod = importlib.import_module(pkg)if pkg in {'PIL'}:ver = mod.VERSIONelse:ver = mod.__version__if Version(ver) < min_ver:print(FAIL, "%s version %s or higher required, but %s installed."% (lib, min_ver, ver))else:print(OK, '%s version %s' % (pkg, ver))except ImportError:print(FAIL, '%s not installed. %s' % (pkg, fail_msg))return mod# first check the python version print('Using python in', sys.prefix) print(sys.version) pyversion = Version(sys.version) if pyversion >= "3":if pyversion < "3.4":print(FAIL, "Python version 3.4 (or 2.7) is required,"" but %s is installed." % sys.version) elif pyversion >= "2":if pyversion < "2.7":print(FAIL, "Python version 2.7 is required,"" but %s is installed." % sys.version) else:print(FAIL, "Unknown Python version: %s" % sys.version)print() requirements = {'numpy': "1.6.1", 'scipy': "0.9", 'matplotlib': "1.0",'IPython': "3.0", 'sklearn': "0.19", 'pandas': "0.18",'seaborn': "0.5", 'PIL': "1.1.7"}# now the dependencies for lib, required_version in list(requirements.items()):import_version(lib, required_version)


References


1小時入門Python
Python學習教程

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的Python 命令汇总的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。