python筆記7:優雅的python

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.