標籤:val 方法 iter == key nbsp 變數 python txt
7. 如何讓python代碼更 Pythonic :
1、變數交換:
a, b = b, a
2、帶有索引位置的集合遍曆:
colors = [‘red‘, ‘green‘, ‘blue‘, ‘yellow‘]for i, color in enumerate(colors):print i, ‘--->‘, color
3、字串串連:
names = [‘raymond‘, ‘rachel‘, ‘matthew‘, ‘roger‘,‘betty‘, ‘melissa‘, ‘judith‘, ‘charlie‘]print ‘, ‘.join(names)
註:使用 + 操作時,每次都會在記憶體中產生一個新的字串對象,而 join 方法整個過程只產生一個字串對象。
4、開啟/關閉檔案:
with open(‘data.txt‘) as f:data = f.read()
註:使用 with 語句,系統會在執行完檔案操作後自動關閉檔案對象。
5、合理使用列表
from collections import dequenames = deque([‘raymond‘, ‘rachel‘, ‘matthew‘, ‘roger‘,‘betty‘, ‘melissa‘, ‘judith‘, ‘charlie‘])names.popleft()#刪除最左邊元素names.appendleft(‘mark‘)#在最左邊添加新元素
註:列表list 是一種查詢效率高於更新操作的資料結構,刪除和插入新元素時效率很低,隊列deque 是一個雙向隊列的資料結構,刪除元素和插入元素會很快
6、序列解包:
p = ‘vttalk‘, ‘female‘, 30, ‘[email protected]‘name, gender, age, email = p
7、遍曆字典的 key 和 value
for k, v in d.iteritems(): 註:iteritems 返回迭代器對象,在python3中只有 items 方法,等值於iteritemsprint k, ‘--->‘, v
8、鏈式比較操作: if 18 < age < 60:
猜一猜:>>> False == False == True (答案為:False)
9、if/else 三目運算:
text = ‘男‘ if gender == ‘male‘ else ‘女‘
10、真值判斷:
if attr: 等價於 if attr == True:if values:(或 not values) 等價於 if len(values) != 0:(或 =0) # 判斷列表是否為空白
11、for/else語句
for else 是 Python 中特有的文法格式,else 中的代碼在 for 迴圈遍曆完所有元素之後執行
12、擷取字典元素
d = {‘name‘: ‘foo‘}d.get("name", "unknow") #如果d有key=name,則獲得其value,否則key=unknow
13、預設字典預設值
(情境:通過 key 分組的時候,不得不每次檢查 key 是否已經存在於字典中。)
groups = {}for (key, value) in data: #方式一,常用groups.setdefault(key, []).append(value)
14、字典推導式
numbers = [1, 2, 3]my_dict = {number: number * 2 for number in numbers if number > 1}print(my_dict) # {2: 4, 3: 6}
15、。。。
python筆記7:優雅的python