# 枚舉
s = ['a', 'b', 'c']
for i, v in enumerate(s):
print(i, v)
# 創建迭代器
class TestIter():
def __init__(self,lst):
self.lst = lst
def __iter__(self):
print('__iter__ is called')
return iter(self.lst)
# t = TestIter()
t = TestIter([1,3,5,7,9])
for e in t:
print(e)
# 同理
for e in t.__iter__():
print(e)
r = [1,2,3]
for i in range(len(r)-1,-1,-1):
print(r[i])
# 打包
# 聚合各個可迭代對象的迭代器:
x = [3,2,1]
y = ['a','b','c']
list(zip(x,y))
for i ,j in zip(y,x):
print(i,j)
# 過濾器
# 函數通過 lambda 表達式設定過濾條件,保留 lambda 表達式爲True的元素:
fil = filter(lambda x: x>10, [1,21,3,4,8,22])
for e in fil:
print(e)
# 鏈式操作
from operator import (add, sub)
def add_or_sub(a,b,oper):
return (add if oper=='+' else sub)(a,b)
# split 分割
s = 'I love python'.split(' ')
# replace 替代
s = 'I love python'.replace(' ', ',')
# 反轉字符串
st = 'python'
''.join(reversed(st))
import time
seconds = time.time() # 當前時間
# 浮點數轉時間結構體
local_time = time.localtime(seconds)
# 時間結構體轉時間字符串
str_time = time.asctime(local_time)
# 時間結構體轉指定格式時間字符串
format_time = time.strftime('%Y.%m%d %H:%M:%S', local_time)
# 時間字符串轉時間結構體
time.strptime(format_time,'%Y.%m.%d %H:%M:%S')
# with 讀寫文件
import os,sys
path = r'G:\Test'
os.listdir(path)
# 讀文件
with open(path, mode='r',encoding='utf-8') as f:
o = f.read()
print(o)
# 寫文件
w_path = r'G:\Test\1.txt'
with open(w_path, mode='w', encoding='utf-8') as f:
w = f.write("I love python \n It\'s so simple")
os.listdir()
# 提取後綴名
import os
os.path.splitext(w_path)