python基礎

一、slicing

# 最后3個元素
>>> a[-3:]
# 除了最后2個元素
>>> a[:,-2]

二、list comprehension

>>> [expression for object in iterable if condition]
>>> [[j,k] for j in range(4) for k in range(4) if j < k]
>>> [s for s in ['aa', ''bb', 'cc'] if 'a' in s]

三、file

file("data.txt", "r").read()  #返回string
file("data.txt", "r").readlines() #返回list
readlines() = read().split('\n')
# gzip 壓縮文件
import gzip
f = gzip.GzipFile("data.txt", "w")
f.write("This is a test for compression.")
f.close()
print gzip.GzipFile("data.txt", "r").read()

四、path

# 生成路徑
>>> p = os.path.join("c:\", "temp", "file.txt")
>>> os.path.exists(p)
>>> os.path.isfile(p)
>>> os.path.isdir(p)
>>> os.path.getsize(p)
>>> os.getcwd()
>>> os.chdir("..")
>>> os.mkdir("c:/temp/newdir") # create a dir
>>> os.remove("c:/temp/deleteme.txt") # delete a file
>>> os.rmdir("c:/temp/newdir") # delete a dir
>>> os.rename("c:/temp/file.txt, "c:/temp/newname.txt") # rename a file

# import shutil # copy和move文件
# import glob  # 找文件名

五、time

>>> import time
>>> time.time() # 返回seconds

t1 = time.time()
ComputerEnergies()
t2 = time.time()
print("The time required was %.2f  sec" % (t2-t1))

# 更簡潔的寫法
import cProfile
cProfile.run("ComputeEngergies()")
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容